spring-boot-starter中默认依赖了spring-boot-starter-logging而他实现的日志组件是Lockback。
事实上官方文档已经讲的非常清楚了,并且提供了两种日志实现的配置Logback和Log4j。具体的官方地址请看:http://docs.spring.io/spring-boot/docs/current/reference/html/howto-logging.html
我们这里主要讲一下如何配置log4j
1、根据官方的方法要想使用log4j,首先得讲默认的log依赖给去除,然后再引入log4j的jar包,pom文件如下:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- 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>
注意:如果你想以yml或者json的方式编写配置文件的话(例如:log4j2.yml或者log4j2.json)官方给出了相应的依赖关系
Format | Dependencies | File names |
---|---|---|
YAML | com.fasterxml.jackson.core:jackson-databind com.fasterxml.jackson.dataformat:jackson-dataformat-yaml | log4j2.yaml log4j2.yml |
JSON | com.fasterxml.jackson.core:jackson-databind | log4j2.json log4j2.jsn |
所以如果我们想和application.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>
添加如上所示的依赖后我们就可以用log4j2.yml去配置了,接下来就直接贴配置详情了
Configuration:
status: warn
Properties: # 定义变量
Property:
- name: log.path
value: d:\\tmp\\logs
- 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.test.dao
additivity: false
level: debug
AppenderRef:
- ref: CONSOLE
- ref: ROLLING_FILE
到这基本上你的log4j2就配置好了。