一,為什么要使用log4j2?
log4j2是log4j的升級版,
升級后更有優勢:
性能更強/吞吐量大/支持異步
功能擴展/支持插件/支持自定義級別等
這些優勢可以從它的官網了解
log4j2官方網站:
https://logging.apache.org/log4j/2.x/
說明:劉宏締的架構森林是一個專注架構的博客,地址:https://www.cnblogs.com/architectforest
對應的源碼可以訪問這里獲取: https://github.com/liuhongdi/
說明:作者:劉宏締 郵箱: 371125307@qq.com
二,本演示項目的相關信息
1,項目地址:
https://github.com/liuhongdi/tomcatlogs
2,項目原理:
生成兩個日志:
bussiness日志:負責記錄業務相關的日志
error日志:負責記錄系統中的錯誤日志
3,項目結構:

三, log4j2的相關配置
1,日志級別的優先級:
ALL < DEBUG < INFO < WARN < ERROR < FATAL < OFF
說明:如果我們設置日志級別為:WARN,
則記錄的級別包括:WARN / ERROR / FATAL / OFF。
2,logger的additivity屬性:
如果設置為false,logger不會把日志流添加到root的日志
如果設置為true,則會添加到root的日志
說明:如果是異步日志時,建議設置為false
3,Appender的immediateFlush屬性:
作用:立刻刷寫到磁盤
如果設置為false,能明顯示的提升性能
即使是同步日志也有幫助
4,
includeLocation=“true”
說明:includeLocation用來獲取類的路徑,
值只有設置為true時才會生效
5,AsyncRoot/AsyncLogger都需要用到disruptor功能,
所以無論用哪個都需要引入disruptor功能包
四,配置文件說明:
1,pom.xml
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <exclusions> <exclusion> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-logging</artifactId> </exclusion> </exclusions> </dependency> <!--log4j2 begin--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-log4j2</artifactId> </dependency> <dependency> <groupId>com.lmax</groupId> <artifactId>disruptor</artifactId> <version>3.4.2</version> </dependency> <!--log4j2 end-->
說明1:spring-boot-starter-web默認包含了日志功能包,
包含了logback/slf4j兩個日志包,
所以我們需要用excusion排除對此兩個包的依賴
說明2:log4j的異步日志使用了Disruptor的隊列技術,
我們需要使用異步日志,所以這里需要引入Disruptor,
附:Disruptor在mvn上的地址:可以從這里查看版本
https://mvnrepository.com/artifact/com.lmax/disruptor
2,application.properties
#log4j2
logging.config=classpath:log4j2.xml
說明:指定log4j2配置文件的路徑,放到resources目錄下
3,log4j2.xml:
<?xml version="1.0" encoding="UTF-8"?> <Configuration status="INFO"> <Appenders> <Console name="STDOUT" target="SYSTEM_OUT"> <PatternLayout pattern=".%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] [%file:%line] %-5level %logger{36} - %msg %n"/> </Console> <RollingFile immediateFlush="false" name="ErrorFile" fileName="/data/logs/tomcatlogs/error.log" filePattern="/data/logs/tomcatlogs/$${date:yyyy-MM}/error-%d{MM-dd-yyyy}-%i.log"> <Filters> <ThresholdFilter level="INFO" /> </Filters> <PatternLayout> <Pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] [%file:%line] %-5level %logger{35} - %msg %n</Pattern> </PatternLayout> <Policies> <TimeBasedTriggeringPolicy /> <SizeBasedTriggeringPolicy size="102400KB"/> </Policies> </RollingFile> <RollingFile immediateFlush="false" name="BusinessFile" fileName="/data/logs/tomcatlogs/bussiness.log" filePattern="/data/logs/tomcatlogs/$${date:yyyy-MM}/bussiness-%d{MM-dd-yyyy}-%i.log"> <PatternLayout> <Pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] [%file:%line] %-5level %logger{35} - %msg %n</Pattern> </PatternLayout> <Policies> <TimeBasedTriggeringPolicy /> <SizeBasedTriggeringPolicy size="102400KB"/> </Policies> </RollingFile> </Appenders> <Loggers> <AsyncLogger name="BusinessFile" level="info" additivity="false"> <appender-ref ref="BusinessFile"/> </AsyncLogger> <AsyncRoot level="info" includeLocation="true"> <AppenderRef ref="STDOUT"/> <AppenderRef ref="ErrorFile" /> </AsyncRoot> </Loggers> </Configuration>
說明:
ErrorFile放到asyncRoot下,用來記錄系統的所有信息
BusinessFile則用來記錄業務相關的日志(需要靠代碼生成日志)
五,java代碼說明
1,homecontroller.java
@RestController @RequestMapping("/home") public class HomeController { @GetMapping("/list") @ResponseBody public String list() { Logger logger1 = LogManager.getLogger(this.getClass()); Logger logger2 = LogManager.getLogger("BusinessFile"); logger1.info("hello,this is in errorlog"); logger2.info("hello,this is in businesslog"); return "this is list"; } }
說明:
獲取logger時,如果使用class,會保存到root下指定的日志
如果使用指定的日志AppenderRef名字,則會保存到名字對應的日志
六,測試寫日志的效果:
1,訪問url
http://127.0.0.1:8080/home/list
2,查看所寫入的日志:
[liuhongdi@localhost tomcatlogs]$ tail -1 bussiness.log 2020-07-05 22:46:07.208 [http-nio-8080-exec-7] [:] INFO BusinessFile - hello,this is in businesslogge [liuhongdi@localhost tomcatlogs]$ tail -1 error.log 2020-07-05 22:46:07.208 [http-nio-8080-exec-7] [HomeController.java:20] INFO com.tomcatlogs.demo.controller.HomeController - hello,this is in errorlog
可以看到日志寫入成功
七,查看spring boot的版本:
. ____ _ __ _ _ /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \ (( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ \\/ ___)| |_)| | | | | || (_| | ) ) ) ) ' |____| .__|_| |_|_| |_\__, | / / / / =========|_|==============|___/=/_/_/_/ :: Spring Boot :: (v2.3.1.RELEASE)