SpringMVC集成LogBack,相关配置
最近在做项⽬中需要⽤到⽇志,本来选取的是Log4j,最后经过对⽐之后还是发现LogBack在性能上⽐Log4j有优势。⾄于有什么好处,请参考下⾯这篇⽂章。
下⾯废话不多说了,就看⼀下,如何来把LogBack集成到我们的web项⽬中吧。本⼈前台⽤的是SpringMVC。
jar包配置
如果要使⽤LogBack做为⽇志的插件的话,需要的jar包有如下,直接看⼀下Maven依赖
1. <span ><dependency>
2. <groupId>org.slf4j</groupId>
3. <artifactId>slf4j-api</artifactId>
4. <version>1.7.12</version>
5. </dependency>
6. <dependency>
7. <groupId>ch.qos.logback</groupId>
8. <artifactId>logback-classic</artifactId>
9. <version>1.1.3</version>
10. <scope>compile</scope>
11. <exclusions>
12. <exclusion>
13. <artifactId>slf4j-api</artifactId>
14. <groupId>org.slf4j</groupId>
15. </exclusion>
16. </exclusions>
17. </dependency>
18.
19. <dependency>
20. <groupId>ch.qos.logback</groupId>
21. <artifactId>logback-core</artifactId>
22. <version>1.1.3</version>
23. <exclusions>
24. <exclusion>
25. <groupId>org.slf4j</groupId>
26. <artifactId>slf4j-api</artifactId>
27. </exclusion>
28. </exclusions>
29. <scope>compile</scope>
30. </dependency>
31.
32. <dependency>
33. <groupId>ch.qos.logback</groupId>
34. <artifactId>logback-access</artifactId>
35. <version>1.1.3</version>
36. <exclusions>
37. <exclusion>
38. <groupId>org.slf4j</groupId>
39. <artifactId>slf4j-api</artifactId>
40. </exclusion>
41. </exclusions>
42. <scope>compile</scope>
43. </dependency></span>
在web项⽬中需要通过l来加载我们所需要的l具体如下
1. <span ><?xml version="1.0" encoding="UTF-8"?>
2. <web-app version="2.5" xmlns="java.sun/xml/ns/javaee"
3. xmlns:xsi="/2001/XMLSchema-instance"
4. xsi:schemaLocation="java.sun/xml/ns/javaee
5. java.sun/xml/ns/javaee/web-app_2_5.xsd">
6.
7.
8.
9.
10. <!-- logback-begin -->
11. <context-param>
12. <param-name>logbackConfigLocation</param-name>
13. <param-value> l</param-value>
14. </context-param>
15. <listener>
16. <listener-class>com.util.LogbackConfigListener</listener-class>
17. </listener>
18. <!-- logback-end -->
19.
20.
21. <filter>
22. <filter-name>encodingFilter</filter-name>
23. <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
24. <init-param>
25. <param-name>encoding</param-name>
26. <param-value>UTF-8</param-value>
27. </init-param>
28. <init-param>
29. <param-name>forceEncoding</param-name>
30. <param-value>true</param-value>
31. </init-param>
32. </filter>
33. <filter-mapping>
34. <filter-name>encodingFilter</filter-name>
35. <url-pattern>/*</url-pattern>
36. </filter-mapping>
37.
38. <servlet>
39. <servlet-name>springMVC</servlet-name>
40. <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
41. <init-param>
42. <param-name>contextConfigLocation</param-name>
43. <param-value> l</param-value>
44. </init-param>
45. <load-on-startup>1</load-on-startup>
46. </servlet>
47. <!-- 这⾥⼀定要是/根据Servlet规范来的 -->
48. <servlet-mapping>
49. <servlet-name>springMVC</servlet-name>
50. <url-pattern>/</url-pattern>
51. </servlet-mapping>
52.
53. </web-app></span>
上⾯的XML中⽤到了⾃定义的,分别是三个类,如下所⽰
LogbackConfigListener类
1. <span >package com.util;
2.
3. import javax.servlet.ServletContextEvent;
4. import javax.servlet.ServletContextListener;
5.
6. public class LogbackConfigListener implements ServletContextListener {
7.
8. public void contextInitialized(ServletContextEvent event) {
9. LogbackWebConfigurer.ServletContext());
10. }
11.
12. public void contextDestroyed(ServletContextEvent event) {
13. LogbackWebConfigurer.ServletContext());
14. }
15. }
16. </span>
LogbackConfigurer类
1. <span >package com.util;
2.
3. import java.io.File;
4. import java.io.FileNotFoundException;
5. import java.URL;
6.
7. import org.slf4j.LoggerFactory;
8. import org.springframework.util.ResourceUtils;
9. import org.springframework.util.SystemPropertyUtils;
10.
11. import ch.qos.logback.classic.LoggerContext;
12. import ch.qos.logback.classic.joran.JoranConfigurator;
13. import ch.joran.spi.JoranException;
14.
15. public abstract class LogbackConfigurer {
16.
17. /** Pseudo URL prefix for loading from the class path: "classpath:" */
18. public static final String CLASSPATH_URL_PREFIX = "classpath:";
19.
20. /** Extension that indicates a logback XML config file: ".xml" */
21. public static final String XML_FILE_EXTENSION = ".xml";
22.
23. private static LoggerContext lc = (LoggerContext) LoggerFactory
24. .getILoggerFactory();
25. private static JoranConfigurator configurator = new JoranConfigurator();
26.
27. /**
28. * Initialize logback from the given file location, with no config file
29. * refreshing. Assumes an XML file in case of a ".xml" file extension, and a
30. * properties file otherwise.
31. *
32. * @param location
33. * the location of the config file: either a "classpath:"
34. * location (e.g. "classpath:mylogback.properties"), an absolute
35. * file URL (e.g.
36. * "file:C:/logback.properties), or a plain absolute path in the file system (e.g. "
37. * C:/logback.properties")
38. * @throws FileNotFoundException
39. * if the location specifies an invalid file path
40. */
41. public static void initLogging(String location)
42. throws FileNotFoundException {
43. String resolvedLocation = SystemPropertyUtils
44. .resolvePlaceholders(location);
45. URL url = URL(resolvedLocation);
46. if (LowerCase().endsWith(XML_FILE_EXTENSION)) {
47. // figure(url);
48. configurator.setContext(lc);
49. lc.reset();
50. try {
51. configurator.doConfigure(url);
52. } catch (JoranException ex) {
53. throw new Path());
54. }
55. lc.start();
56. }
57. // else {
58. // figure(url);
59. // }
60. }
61.
62. /**
63. * Shut down logback, properly releasing all file locks.
64. * <p>
65. * This isn't strictly necessary, but recommended for shutting down logback
66. * in a scenario where the host VM stays alive (for example, when shutting
67. * down an application in a J2EE environment).
68. */
69. public static void shutdownLogging() {
70. lc.stop();
71. }
72.
73. /**
74. * Set the specified system property to the current working directory.
75. * <p>
76. * This can be for test environments, for applications that
77. * leverage logbackWebConfigurer's "webAppRootKey" support in a web
78. * environment.
79. *
80. * @param key
81. * system property key to use, as expected in logback
82. * configuration (for example: "", used as
83. * "${}/WEB-INF/demo.log")
84. * @see org.springframework.web.util.logbackWebConfigurer
85. */
86. public static void setWorkingDirSystemProperty(String key) {
87. System.setProperty(key, new File("").getAbsolutePath());
88. }
89.
90. }
91. </span>
LogbackWebConfigurer类
1. <span >package com.util;
2.
3. import java.io.FileNotFoundException;
4.
5. import javax.servlet.ServletContext;
6.
7. import org.springframework.util.ResourceUtils;
8. import org.springframework.util.SystemPropertyUtils;
9. import org.springframework.web.util.WebUtils;
10.
11. public abstract class LogbackWebConfigurer {
12.
13. /** Parameter specifying the location of the logback config file */
14. public static final String CONFIG_LOCATION_PARAM = "logbackConfigLocation";
15.
16. /**
17. * Parameter specifying the refresh interval for checking the logback config
18. * file
19. */
20. public static final String REFRESH_INTERVAL_PARAM = "logbackRefreshInterval";
21.
22. /** Parameter specifying whether to expose the web app root system property */
23. public static final String EXPOSE_WEB_APP_ROOT_PARAM = "logbackExposeWebAppRoot";
24.
25. /**
26. * Initialize logback, including setting the web app root system property.
27. *
28. * @param servletContext
29. * the current ServletContext
30. * @see WebUtils#setWebAppRootSystemProperty
31. */
32. public static void initLogging(ServletContext servletContext) {
33. // Expose the web app root system property.
34. if (exposeWebAppRoot(servletContext)) {
35. WebUtils.setWebAppRootSystemProperty(servletContext);
36. }
37.
38. // Only perform custom logback initialization in case of a config file.
39. String location = servletContext
40. .getInitParameter(CONFIG_LOCATION_PARAM);
41. if (location != null) {
42. // Perform actual logback initialization; else rely on logback's
43. // default initialization.
44. try {
45. // Return a URL (e.g. "classpath:" or "file:") as-is;
46. // consider a plain file path as relative to the web application
47. // root directory.
48. if (!ResourceUtils.isUrl(location)) {
49. // Resolve system property placeholders before resolving
50. // real path.
51. location = SystemPropertyUtils
52. .resolvePlaceholders(location);
53. location = RealPath(servletContext, location);
54. }
55.
56. // Write log message to server log.
57. servletContext.log("Initializing logback from [" + location
58. + "]");
59.
60. // Initialize without refresh check, i.e. without logback's
61. // watchdog thread.
62. LogbackConfigurer.initLogging(location);
63.
64. } catch (FileNotFoundException ex) {
65. throw new IllegalArgumentException(
66. "Invalid 'logbackConfigLocation' parameter: "
67. + ex.getMessage());
68. }
69. }
70. }
71.
72. /**
73. * Shut down logback, properly releasing all file locks and resetting the
74. * web app root system property.
75. *
76. * @param servletContext
77. * the current ServletContext
78. * @see WebUtils#removeWebAppRootSystemProperty
79. */
80. public static void shutdownLogging(ServletContext servletContext) {
81. servletContext.log("Shutting down logback");
82. try {
83. LogbackConfigurer.shutdownLogging();
84. } finally {
85. // Remove the web app root system property.
86. if (exposeWebAppRoot(servletContext)) {
87. veWebAppRootSystemProperty(servletContext);
88. }
89. }
90. }
91.
92. /**
93. * Return whether to expose the web app root system property, checking the
94. * corresponding ServletContext init parameter.
log4j2xml配置95. *
96. * @see #EXPOSE_WEB_APP_ROOT_PARAM
97. */
98. private static boolean exposeWebAppRoot(ServletContext servletContext) {
99. String exposeWebAppRootParam = servletContext
100. .getInitParameter(EXPOSE_WEB_APP_ROOT_PARAM);
101. return (exposeWebAppRootParam == null || Boolean
102. .valueOf(exposeWebAppRootParam));
103. }
104.
105. }
106. </span>
logback.XML配置
下⾯来看⼀下这个xml是如何配置的
1. <span ><?xml version="1.0" encoding="UTF-8"?>
2. <!-- ROOT 节点 -->
3. <!-- 属性描述 scan:性设置为true时,配置⽂件如果发⽣改变,将会被重新加载,默认值为true scanPeriod:设置监测配置⽂件是否有修改的时间间隔,如果没有给出时间单位,默认单位是毫秒。当scan为true时,此属性⽣效。默认的时间间隔
4. debug:当此属性设置为true时,将打印出logback内部⽇志信息,实时查看logback运⾏状态。默认值为false。 -->
5. <configuration scan="true" scanPeriod="60 seconds" debug="false">
6. <!-- 定义⽇志⽂件输⼊位置,注意此处的/ -->
7. <property name="log_dir" value="E:/logs" />
8. <!-- ⽇志最⼤的历史 60天 -->
9. <property name="maxHistory" value="60"></property>
10.
11.
12. <!-- 控制台输出⽇志 -->
13. <appender name="STDOUT" class="ch.ConsoleAppender">
14. <encoder>
15. <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger -
16. %msg%n</pattern>
17. </encoder>
18.
19. </appender>
20.
21.
22. <!-- 出错⽇志 appender -->
23. <appender name="ERROR"
24. class="ch.olling.RollingFileAppender">
25. <!-- 在多数的Log⼯具中,级别是可以传递,例如如果指定了⽇志输出级别为DEBUG,那么INFO、ERROR级别的log也会出现在⽇志⽂件。这种默认给程序的调试带来了很多的⿇烦
26. 通过配置Filter 来严格控制⽇志输⼊级别 <filter class="ch.qos.logback.classic.filter.LevelFilter">
27. <level>ERROR/level> <onMatch>ACCEPT</onMatch> <onMismatch>DENY</onMismatch>
28. </filter> -->
29. <rollingPolicy class="ch.olling.TimeBasedRollingPolicy">
30. <!-- 按天回滚 daily -->
31. <fileNamePattern>${log_dir}/error-log-%d{yyyy-MM-dd}.log
32. </fileNamePattern>
33. <!-- ⽇志最⼤的历史 60天 -->
34. <maxHistory>${maxHistory}</maxHistory>
35. </rollingPolicy>
36. <encoder>
37. <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger -
38. %msg%n</pattern>
39. </encoder>
40. </appender>
41.
42. <!-- INFO ⽇志 appender -->
43. <appender name="INFO"
44. class="ch.olling.RollingFileAppender">
45. <rollingPolicy class="ch.olling.TimeBasedRollingPolicy">
46. <!-- 按天回滚 daily -->
47. <fileNamePattern>${log_dir}/info-log-%d{yyyy-MM-dd}.log
48. </fileNamePattern>
49. <!-- ⽇志最⼤的历史 60天 -->
50. <maxHistory>${maxHistory}</maxHistory>
51. </rollingPolicy>
52. <encoder>
53. <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger -
54. %msg%n</pattern>
55. </encoder>
56. </appender>
57.
58.
59. <!-- 访问⽇志 appender -->
60. <appender name="ACCESS"
61. class="ch.olling.RollingFileAppender">
62. <rollingPolicy class="ch.olling.TimeBasedRollingPolicy">
63. <!-- 按天回滚 daily -->
64. <fileNamePattern>${log_dir}/access-log-%d{yyyy-MM-dd}.log
65. </fileNamePattern>
66. <!-- ⽇志最⼤的历史 60天 -->
67. <maxHistory>${maxHistory}</maxHistory>
68. </rollingPolicy>
69. <encoder>
70. <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger -
71. %msg%n</pattern>
72. </encoder>
73. </appender>
74.
75. <!-- 系统⽤户操作⽇志 appender -->
76. <appender name="SYS-USER"
77. class="ch.olling.RollingFileAppender">
78. <rollingPolicy class="ch.olling.TimeBasedRollingPolicy">
79. <!-- 按天回滚 daily -->
80. <fileNamePattern>${log_dir}/sys_user-log-%d{yyyy-MM-dd}.log
81. </fileNamePattern>
82. <!-- ⽇志最⼤的历史 60天 -->
83. <maxHistory>${maxHistory}</maxHistory>
84. </rollingPolicy>
85. <encoder>
86. <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger -
87. %msg%n</pattern>
88. </encoder>
89. </appender>
90.
91.
92. <!-- 打印SQL输出 -->
93. <logger name="java.sql.Connection" level="DEBUG" />
94. <logger name="java.sql.Statement" level="DEBUG" />
95. <logger name="java.sql.PreparedStatement" level="DEBUG" />
96.
97.
98.
99. <!--error错误⽇志 additivity="false"表⽰不向上传递 -->
100. <!-- <logger name="st" level="error" > -->
101. <!-- <appender-ref ref="ERROR" /> -->
102. <!-- </logger> -->
103. <!--info⽇志 -->
104. <logger name="st" level="info" additivity="false">
105. <appender-ref ref="INFO" />
106. </logger>
107. <!--访问⽇志 -->
108. <!-- <logger name="st" level="info" additivity="false"> -->
109. <!-- <appender-ref ref="ACCESS" /> -->
110. <!-- </logger> -->
111. <!--系统⽤户操作⽇志 -->
112. <!-- <logger name="st" level="info" additivity="false"> -->
113. <!-- <appender-ref ref="SYS-USER" /> -->
114. <!-- </logger> -->
115.
116. <root>
117. <level value="INFO" />
118. <appender-ref ref="stdout" />
119. </root>
120. </configuration></span>
关于这个XML⽂件的详细讲解请参考
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论