SpringBoot 配置log4j2日志输出
可以有两种优雅一点的方式:
格式 | 依赖包 | 文件名 |
---|---|---|
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 |
pom.xml
排除 web 包中的 logging
,
引入log4j2
依赖和yaml
文件识别。
<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依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-log4j2</artifactId>
</dependency>
<!-- 加上这个才能辨认到log4j2.yml文件 -->
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-yaml</artifactId>
</dependency>
log4j2.yaml
在 resources
文件夹下增加 log4j2.yaml
文件。
Configuration:
status: warn
Properties: # 定义全局变量
Property: # 缺省配置(用于开发环境)。其他环境需要在VM参数中指定,如下:
# 测试:-Dlog.level.console=warn -Dlog.level.xjj=trace
# 生产:-Dlog.level.console=warn -Dlog.level.xjj=info
- name: log.level.console
value: trace
- name: log.level.com.jeiker.demo.mapper
value: trace
- name: log.path
value: /opt/logs
- name: project.name
value: my-app
Appenders:
Console: # 输出到控制台
name: CONSOLE
target: SYSTEM_OUT
ThresholdFilter:
level: ${sys:log.level.console} # “sys:”表示:如果VM参数中没指定这个变量值,则使用本文件中定义的缺省全局变量值
onMatch: ACCEPT
onMismatch: DENY
PatternLayout:
pattern: "%d{yyyy-MM-dd HH:mm:ss,SSS}:%5p %20t [%50F:%3L] - %m%n"
RollingFile: # 输出到文件,超过128MB归档
- 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}:%5p %20t [%50F:%3L] - %m%n"
Policies:
SizeBasedTriggeringPolicy:
size: "128 MB"
DefaultRolloverStrategy:
max: 1000
Loggers:
Root:
level: info
AppenderRef:
- ref: CONSOLE
- ref: ROLLING_FILE
Logger: # 为 com.jeiker.demo.mapper 包配置特殊的Log级别,方便调试 SQL 语句输出
- name: log.level.com.jeiker.demo.mapper
additivity: false
level: ${sys:log.level.com.jeiker.demo.mapper}
AppenderRef:
- ref: CONSOLE
- ref: ROLLING_FILE