一、背景
最近因為公司專案效能需要,我們考慮把以前基於的log4j的日誌系統重構成基於Slf4j和log4j2的日誌系統,因為,使用slf4j可以很好的保證我們的日誌系統具有良好的相容性,相容當前常見幾種日誌系統,而使用log4j2而不是log4j是因為Log4j 1.x 在高併發情況下出現死鎖導致cpu使用率異常飆升,而Log4j2.0基於LMAX Disruptor的非同步日誌在多執行緒環境下效能會遠遠優於Log4j 1.x和logback(官方資料是10倍以上)。
關於slf4j的原理以及優點,請參見我的另一篇部落格:slf4j介紹以及實現原理窺探
二、搭建步驟
1.依賴管理
1).刪除專案中存在的Log4j1.x所必須的log4j和slf4j-log4j12等依賴。
可以到專案的根目錄,執行:mvn dependency:tree > tree.log,之後使用 cat tree.log | grep log4j命令進行查詢。
1 <exclusions> 2 <exclusion> 3 <groupId>org.slf4j</groupId> 4 <artifactId>slf4j-log4j12</artifactId> 5 </exclusion> 6 <exclusion> 7 <groupId>log4j</groupId> 8 <artifactId>log4j</artifactId> 9 </exclusion> 10 </exclusions>
2).新增以下slf4j和log4j2的依賴.
1 <!-- slf4j核心包--> 2 <dependency> 3 <groupId>org.slf4j</groupId> 4 <artifactId>slf4j-api</artifactId> 5 <version>1.7.13</version> 6 </dependency> 7 <dependency> 8 <groupId>org.slf4j</groupId> 9 <artifactId>jcl-over-slf4j</artifactId> 10 <version>1.7.13</version> 11 <scope>runtime</scope> 12 </dependency> 13 14 <!--核心log4j2jar包--> 15 <dependency> 16 <groupId>org.apache.logging.log4j</groupId> 17 <artifactId>log4j-api</artifactId> 18 <version>2.4.1</version> 19 </dependency> 20 <dependency> 21 <groupId>org.apache.logging.log4j</groupId> 22 <artifactId>log4j-core</artifactId> 23 <version>2.4.1</version> 24 </dependency> 25 <!--用於與slf4j保持橋接--> 26 <dependency> 27 <groupId>org.apache.logging.log4j</groupId> 28 <artifactId>log4j-slf4j-impl</artifactId> 29 <version>2.4.1</version> 30 </dependency> 31 <!--web工程需要包含log4j-web,非web工程不需要--> 32 <dependency> 33 <groupId>org.apache.logging.log4j</groupId> 34 <artifactId>log4j-web</artifactId> 35 <version>2.4.1</version> 36 <scope>runtime</scope> 37 </dependency> 38 39 <!--需要使用log4j2的AsyncLogger需要包含disruptor--> 40 <dependency> 41 <groupId>com.lmax</groupId> 42 <artifactId>disruptor</artifactId> 43 <version>3.2.0</version> 44 </dependency>
2.web.xml中設定log4j2的監聽器和過濾器(servlet3.0及以上版本不需要該步操作)
1 <!--對於log4j2,Servlet2.5以前的版本需要--> 2 <listener> 3 <listener-class>org.apache.logging.log4j.web.Log4jServletContextListener</listener-class> 4 </listener> 5 <filter> 6 <filter-name>log4jServletFilter</filter-name> 7 <filter-class>org.apache.logging.log4j.web.Log4jServletFilter</filter-class> 8 </filter> 9 <filter-mapping> 10 <filter-name>log4jServletFilter</filter-name> 11 <url-pattern>/*</url-pattern> 12 <dispatcher>REQUEST</dispatcher> 13 <dispatcher>FORWARD</dispatcher> 14 <dispatcher>INCLUDE</dispatcher> 15 <dispatcher>ERROR</dispatcher> 16 </filter-mapping>
注意:log4j2不再支援properties檔案了,只支援xml,json或是yaml,不指定位置的情況下預設在src/main/resources下查詢。
如果需要自定義位置,需要在上面的web.xml中新增以下程式碼
1 <context-param> 2 <param-name>log4jConfiguration</param-name> 3 <param-value>/WEB-INF/classes/log4j2.xml</param-value> 4 </context-param>
3.log4j2.xml
1 <?xml version="1.0" encoding="UTF-8"?> 2 3 <Configuration status="off" monitorInterval="1800"> 4 5 <properties> 6 <property name="LOG_HOME">/opt/logs/hafiz/log4j2Demo/logs</property> 7 <property name="ERROR_LOG_FILE_NAME">error</property> 8 </properties> 9 10 11 <Appenders> 12 <Console name="Console" target="SYSTEM_OUT"> 13 <PatternLayout pattern="%d %-5p (%F:%L) - %m%n" /> 14 </Console> 15 16 <RollingRandomAccessFile name="ErrorLog" 17 fileName="${LOG_HOME}/${ERROR_LOG_FILE_NAME}.log" 18 filePattern="${LOG_HOME}/${ERROR_LOG_FILE_NAME}.log.%d{yyyy-MM-dd}.gz"> 19 <PatternLayout 20 pattern="%d %-5p (%F:%L) - %m%n"/> 21 <Policies> 22 <TimeBasedTriggeringPolicy/> 23 <SizeBasedTriggeringPolicy size="100 MB"/> 24 </Policies> 25 <DefaultRolloverStrategy max="20"/> 26 </RollingRandomAccessFile> 27 28 </Appenders> 29 30 <Loggers> 31 <!-- 3rdparty Loggers --> 32 <logger name="org.springframework.core" level="info"> 33 </logger> 34 <logger name="org.springframework.beans" level="info"> 35 </logger> 36 <logger name="org.springframework.context" level="info"> 37 </logger> 38 <logger name="org.springframework.web" level="info"> 39 </logger> 40 41 <logger name="com.hafiz.www.controller" level="error" includeLocation="true" additivity="false"> 42 <appender-ref ref="ErrorLog"/> 43 <appender-ref ref="Console"/> 44 </logger> 45 46 <root level="info" includeLocation="true"> 47 <appender-ref ref="Console"/> 48 </root> 49 </Loggers> 50 </Configuration>
4.測試類UserController.java
1 package com.hafiz.www.controller; 2 3 import com.hafiz.www.po.UserEntity; 4 import com.hafiz.www.service.UserService; 5 import org.slf4j.Logger; 6 import org.slf4j.LoggerFactory; 7 import org.springframework.beans.factory.annotation.Autowired; 8 import org.springframework.stereotype.Controller; 9 import org.springframework.web.bind.annotation.RequestMapping; 10 import org.springframework.web.bind.annotation.RequestMethod; 11 import org.springframework.web.bind.annotation.ResponseBody; 12 13 import java.util.ArrayList; 14 import java.util.List; 15 16 /** 17 * Desc:使用者資訊控制器 18 * Created by hafiz.zhang on 2016/8/27. 19 */ 20 @Controller 21 @RequestMapping("/user") 22 public class UserController { 23 24 private static final Logger logger = LoggerFactory.getLogger(UserController.class); 25 26 @Autowired 27 private UserService userService; 28 29 @RequestMapping(value = "/all", method = RequestMethod.GET) 30 @ResponseBody 31 public List<UserEntity> getAllUsers(){ 32 logger.info("[GET] /user/all getAllUsers"); 33 List<UserEntity> list = userService.getAllUsers(); 34 logger.debug("This is log of level of debug"); 35 logger.trace("log4j2 Demo"); 36 logger.error("哎呀,出錯啦~"); 37 return list; 38 } 39 }
注意:在JVM啟動引數中增加 -DLog4jContextSelector=org.apache.logging.log4j.core.async.AsyncLoggerContextSelector 開啟非同步日誌.
三、小問題:
專案不列印日誌並且報:SLF4J: Class path contains multiple SLF4J bindings.主要問題在於在專案中既存在slf4j-log4j12的jar包又存在log4j-slf4j-impl的jar包,導致出現了兩個列印日誌實現類,所以slf4j門面不知道具體應該使用哪一個進行輸出日誌,所以導致不列印日誌。
因為我之前是log4j 1.x,並且我在web.xml裡面指定了log4j.properties檔案的位置,第一次執行專案,忘了修改其值為log4j2.xml,出現了"Context [] startup failed due to previous errors"的錯誤,導致專案啟動不起來,web.xml中修改為如下方式以後就正常了。
1 <context-param> 2 <param-name>log4jConfiguration</param-name> 3 <param-value>/WEB-INF/classes/log4j2.xml</param-value> 4 </context-param>