spring boot內(nèi)部使用Commons Logging來記錄日志段化,但也保留外部接口可以讓一些日志框架來進行實現(xiàn),例如Log4J2, Logback造成。spring boot使用Logback作為日志實現(xiàn)的框架显熏。
今天整理這個文章的原因就是網(wǎng)上有很多Log4J2的配置博客,但是有一大半都是轉(zhuǎn)載的晒屎,而且配置也是不完全的喘蟆。下面是實際操作的具體步驟现诀。
1:在pom中引入Log4j2的依賴,同時exclusion 掉spring boot自帶的logging back
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-log4j2</artifactId>
</dependency>
2:在配置文件application.properties添加log4j2的配置
logging.config=classpath:log4j2.xml
3:在 src/main/resources 創(chuàng)建log4j2.xml 并寫入如下配置
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="INFO">
<!—設(shè)置一個控制臺log輸出器-->
<Appenders>
<Console name="Console" target="SYSTEM_OUT" follow="true">
<PatternLayout>
<pattern>[%-5p] %d %c - %m%n</pattern>
</PatternLayout>
</Console>
<!—設(shè)置一個文件log輸出器-->
<File name="File" fileName="../../logs/gather-plugin/sisc-gather-plugin.log" append="false">
<PatternLayout>
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} - %msg%xEx%n</pattern>
</PatternLayout>
</File>
</Appenders>
<Loggers>
<Root level="INFO">
<AppenderRef ref="Console"/>
<!--所有的log都輸出到console-->
</Root>
<!—只捕獲com.cxy.xxx.service下的的log都輸出到log文件中-->
<Logger name="com.cxy.xxx.service" level="INFO" additivity="false">
<AppenderRef ref="File" />
<!--只有com.cxy.xxx.service包下的 log 才會輸出到文件-->
</Logger>
</Loggers>
</Configuration>
Additivity=false; 表示每次重啟項目履肃,將log文件情況仔沿,改為true表示重啟后追加log
上面就是spring boot 整合 log4j2的完整配置步驟。