Spring boot配置log4g2
首先log4j不在更新
官網:
End of Life On August 5, 2015 the Logging Services Project Management
Committee announced that Log4j 1.x had reached end of life. For
complete text of the announcement please see the Apache Blog. Users of
Log4j 1 are recommended to upgrade to Apache Log4j 2.
是的,log4j停止於1.x版本,迎來了log4j 2,也就是我們今天要說的log4j 2.
配置說明:
pom文件需要去除log4j 引用並添加log4j2引用
<!-- exclude默認logging依賴 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- 添加log4j2的依賴 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-log4j2</artifactId>
</dependency>
log4j2配置文件
首先log4j2的配置文件不在使用*.properties文件而是使用更易讀的:
log4j2.yml和log4j2.xml,將文件放在項目resources中即可。
我的配置:log4j2.yml
Configuration:
status: DEBUG
Properties: # 定義變量
Property:
- name: log.path
value: /Users/rock/projects/log
- name: project.name
value: spring-boot-log
Appenders:
Console: #輸出到控制檯
name: CONSOLE
target: SYSTEM_OUT
ThresholdFilter:
level: trace
onMatch: ACCEPT
onMismatch: DENY
PatternLayout:
pattern: "%d{yyyy-MM-dd HH:mm:ss,SSS}:%4p %t (%F:%L) - %m%n"
# 輸出到文件,超過128MB歸檔
RollingFile:
- name: ROLLING_FILE
ignoreExceptions: false
fileName: ${log.path}/${project.name}.log
filePattern: "${log.path}/$${date:yyyy-MM}/${project.name}-%d{yyyy-MM-dd}-%i.log.gz"
PatternLayout:
pattern: "%d{yyyy-MM-dd HH:mm:ss,SSS}:%4p %t (%F:%L) - %m%n"
Policies:
SizeBasedTriggeringPolicy:
size: "128 MB"
DefaultRolloverStrategy:
max: 1000
Loggers:
Root:
level: info
AppenderRef:
- ref: CONSOLE
- ref: ROLLING_FILE
Logger: # 爲com.xjj包配置特殊的Log級別,方便調試
- name: com.example
additivity: false
level: debug
AppenderRef:
- ref: CONSOLE
- ref: ROLLING_FILE
注意支持yml解析文件需要引入:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-yaml</artifactId>
</dependency>
項目中引用log4j Logger時候注意包區別:
log4j:
import org.apache.log4j.Logger;
private final Logger LOGGER = Logger.getLogger(Test.class.getName());
log4j2:
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
private static Logger logger = LogManager.getLogger(Test.class.getName());
有問題請回復或者留下聯繫方式一起討論