背景
自从 log4j2 发布后,就一直在使用 slf4j + log4j2 了,最近在用 Spring Cloud 搭建项目,于是就研究了一下如何在 Spring Cloud 中引入 log4j2 。之前对比了 XML 和 Properties 的方式进行配置,感觉 XML 配置更易理解,后来学习 Spring Boot 框架,由于 Spring Boot 的很多资料都使用了 YAML 语法的配置文件,使用之后感觉,相对于 XML 和 Properties 配置,YAML 语法层次感更强,看起来确实更清晰,于是这次决定使用 YAML 语法对 log4j 进行配置。
排除对 logback 的依赖
看了一下依赖关系,发现 spring-boot-starter(version = 1.4.3.RELEASE) 依赖 spring-boot-starter-logging(version = 1.4.3.RELEASE),而 spring-boot-starter-logging 使用了 slf4j + logback,因此这里首先需要排除对 logback 的依赖,在 build.gradle 中加入如下配置:1
2
3
4configurations {
// 在整个构建过程中排除 `ch.qos.logback:logback-classic`
all*.exclude group: 'ch.qos.logback', module: 'logback-classic'
}
添加 log4j2 依赖
Spring Boot 已经提供了 log4j2 对应的 Starter 模块 spring-boot-starter-log4j2,这里我们可以直接在 build.gradle 中引入:1
2
3
4
5dependencies {
// ...
compile 'org.springframework.boot:spring-boot-starter-log4j2:+'
// ...
}
log4j2.yml 内容如下:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21Configuration:
status: warn
name: YAMLConfig
properties:
property:
name: project.name
value: spring-cloud-demo
property:
name: pattern
value: "%d %-5p [%c]\\: %L - %m%n"
appenders:
Console:
name: STDOUT
PatternLayout:
Pattern: ${pattern}
Loggers:
Root:
level: debug
AppenderRef:
ref: STDOUT
运行项目发现会报如下异常提示信息:1
ERROR StatusLogger No log4j2 configuration file found. Using default configuration: logging only errors to the console.
添加 com.fasterxml.jackson 依赖
查看 log4j2 关于如何 log4j2 如何查找配置文件的的介绍,log4j2 会按照
> 01. -Dlog4j.configurationFile
> 02. classpath:log4j2-test.properties
> 03. classpath:log4j2-test.yaml
> 04. classpath:log4j2-test.yml
> 05. classpath:log4j2-test.json
> 06. classpath:log4j2-test.jsn
> 07. classpath:log4j2-test.xml
> 08. classpath:log4j2.properties
> 09. classpath:log4j2.yaml
> 10. classpath:log4j2.yml
> 11. classpath:log4j2.json
> 12. classpath:log4j2.jsn
> 13. classpath:log4j2.xml
> 14. DefaultConfiguration
的顺序查找配置文件,发现并没有问题,那又是为什么呢?
查看 log4j2 文档后发现,使用 YAML 格式的配置,需要依赖 jackson 的几个包,在 build.gradle 中追加以下依赖:1
2
3
4
5
6
7
8dependencies {
// ...
compile 'com.fasterxml.jackson.core:jackson-databind:+'
compile 'com.fasterxml.jackson.core:jackson-core:+'
compile 'com.fasterxml.jackson.dataformat:jackson-dataformat-yaml:+'
compile 'com.fasterxml.jackson.core:jackson-annotations:+'
}
// ...
再次启动项目,可以正常输出日志。