其实官网已经说的比较清楚了:https://logging.apache.org/log4j/2.x/manual/customconfig.html
下面根据自己的实践稍微总结一下:
1、编写 自定义ConfigurationFactory 继承自org.apache.logging.log4j.core.config.ConfigurationFactory。命名为CustomConfigurationFactory,具体代码怎么实现可以看官网。
2、在spring boot 入口类中加入如下代码之一:
System.setProperty("log4j.configurationFactory","com.gionee.cloud.genny.trace.CustomConfigurationFactory");
或者
ConfigurationFactory.setConfigurationFactory(new CustomConfigurationFactory());
3、修改依赖配置,我用的是gradle,如下:
compile ('org.springframework.boot:spring-boot-starter')
{
exclude module: 'spring-boot-starter-logging'
exclude module: 'logback-classic'
}
compile ('org.springframework.boot:spring-boot-starter-web')
{
exclude module: 'spring-boot-starter-logging'
exclude module: 'logback-classic'
}
compile 'org.springframework.boot:spring-boot-starter-log4j2'
或者追求log4j2新新版本的可以不用spring boot自带的,如下:
compile ('org.springframework.boot:spring-boot-starter')
{
exclude module: 'spring-boot-starter-logging'
exclude module: 'logback-classic'
}
compile ('org.springframework.boot:spring-boot-starter-web')
{
exclude module: 'spring-boot-starter-logging'
exclude module: 'logback-classic'
}
compile 'org.apache.logging.log4j:log4j-api:2.8.2'
compile 'org.apache.logging.log4j:log4j-core:2.8.2'
当然了你也可以不用 exclude spring boot默认的日志。但是这样的后果就是:有两套日志系统,不建议这么干。既然要用就是统一为log4j2.
上一篇文章中总结了容易犯错的地方,这里再重申一下,因为一不小心就被你踩中了:
1、在入口类中,不可有如下的类变量申明:
private static final Logger logger = LogManager.getLogger(App.class);
2、如果采取编程式配置,则spring boot框架不会去加载log4j2.xml文件,即使有也不会加载,也就是说失效了(混合式除外)。
3、编程式配置的3中方法——一定要写在入口类的最前面,保证首先执行:
1)、申明系统变量System.setProperty("log4j.configurationFactory","com.gionee.cloud.genny.trace.CustomConfigurationFactory");
2)、ConfigurationFactory.setConfigurationFactory(new CustomConfigurationFactory());
3)、插件形式System.setProperty("log4j.plugin.packages","com.gionee.cloud.genny.trace.*");(此方法一直没成功,推荐用前面两种其中之一)
注:一定要注意第一点,否则不能保证第三点首先执行。