1. 程式人生 > >在spring boot中log4j2程式設計式配置(Programmatic Configuration)步驟

在spring boot中log4j2程式設計式配置(Programmatic Configuration)步驟

下面根據自己的實踐稍微總結一下:

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.*");(此方法一直沒成功,推薦用前面兩種其中之一)

注:一定要注意第一點,否則不能保證第三點首先執行。