原创文章,转载请注明
spring-boot中使用log4j2其实非常简单,因为spring-boot本身也使用了,而且还不止log4j2。我们如果要用的话必须把spring-boot-starter-logging的依赖去掉,不然会是spring-boot默认的日志,该starter在spring-boot-starter中。既然去除了官方的日志依赖,同时也去除了log4j2的依赖,因此我们还需要把log4j2的依赖加进来。
之后就可以自己配置log4j2了,官方的说明文档在76.2章节。
摘录如下:
76.2 Configure Log4j for logging
Spring Boot supports Log4j 2 for loggingconfiguration if it is on the classpath. If you are using the starters forassembling dependencies that means you have to exclude Logback and then include log4j 2instead. If you aren’t using the starters then you need to providejcl-over-slf4j
(at least) in addition to Log4j 2.
The simplest path is probably through the starters, even though it requires somejiggling with excludes, .e.g. in Maven:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<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>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-log4j2</artifactId>
</dependency>
The use of the Log4j starters gathers together the dependencies for common loggingrequirements (e.g. including having Tomcat use |
76.2.1 Use YAML or JSON to configure Log4j 2
In addition to its default XML configuration format, Log4j 2 also supports YAML and JSONconfiguration files. To configure Log4j 2 to use an alternative configuration file format,add the appropriate dependencies to the classpath and name yourconfiguration files to match your chosen file format:
Format | Dependencies | File names |
---|---|---|
YAML |
|
|
JSON |
|
|