springboot + gradle 集成log4j2

4,680 阅读1分钟

exclude springboot自带的日志框架

springboot 本身自带logback日志框架 以及项目中的其它依赖可能带有日志框架, 因此需要在gradle全局禁用其它日志框架

configurations.all {
    exclude group:'org.springframework.boot', module: 'spring-boot-starter-logging'
    exclude module: 'logback-classic'
    exclude module: 'logback-core'
}

通常exclude的两种方式

方式1

如果build.gradle中没有分项目的话, exclude就是放在文件中, 和dependencies同级即可

移除前: 移除后:

方式二

如果build.gradle分项目了 其中settings.gradle如下,有rootProject 并且include了多个项目

rootProject.name = 'gradletest'
include 'app'
include 'module1'
include 'module2'

那么exclude就需要放在subprojects代码块中, 就会对所有子项目(所有子项目合起来就是你的项目)生效

subprojects {
    // 省略其它内容
    configurations.all {
        exclude group:'org.springframework.boot', module: 'spring-boot-starter-logging'
        exclude module: 'logback-classic'
        exclude module: 'logback-core'
    }
}

引入log4j2依赖

如果springboot项目继承了spring-boot-starter-parent, 使用起步依赖, log4j2依赖可以不用加依赖版本号

compile 'org.springframework.boot:spring-boot-starter-log4j2'

否则需要加依赖版本号

compile 'org.springframework.boot:spring-boot-starter-log4j2:2.4.0'

添加log4j2-spring.xml文件

在项目合适位置的resource中添加log4j2的配置文件

如果自定义了文件名(包括log4j2.xml这个文件名),需要在application.yml中配置

logging:
  config: xxxx.xml

默认名log4j2-spring.xml,使用该名称就无需在application.yml中额外配置

log4j2-spring.xml具体如何配置可以参考我的另一篇文章

log4j2 配置文件不全面解析