官网:
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的配置文件不在使用*.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
<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());
有问题请回复或者留下联系方式一起讨论