從Log4j切換到Log4j2,沒有打包之前日志輸出正常,但是打包后總是提示下面內容:
錯誤一:
ERROR StatusLogger Log4j2 could not find a logging implementation. Please add log4j-core to the classpath. Using SimpleLogger to log to the console...
錯誤二:
ERROR StatusLogger LogManager returned an instance of org.apache.logging.log4j.simple.SimpleLoggerContextFactory which does not implement org.apache.logging.log4j.core.impl.Log4jContextFactory. Unable to initialize Log4j.
被這個問題折騰了一天多,總算是找到一個解決辦法,在這里記錄一下。
錯誤一:
網上有人說是沒有導入log4j-core,但是導入后還是出現這個錯誤。
有人說log4j2有個加載配置文件的順序(https://logging.apache.org/log4j/2.x/manual/configuration.html),所以試了各種名字,還是失敗。
這里還嘗試了添加啟動參數(-Dlog4j.configurationFile=log4j2.xml),以及在src下添加log4j2.component.properties文件(內容:log4j.configurationFile=log4j2.xml),結果同樣失敗。
錯誤二:
這個問題在網上沒有多少可以參考的信息,但是在解決錯誤一時,看到有log4j2.component.properties這個配置文件,所以抱着試試的態度,到官方上查了一下,有這樣的內容:
https://logging.apache.org/log4j/2.x/manual/configuration.html#SystemProperties

然后果斷在src下添加log4j2.component.properties文件(內容:log4j2.loggerContextFactory=org.apache.logging.log4j.core.impl.Log4jContextFactory),接着打包運行,日志正常輸出了。鼓掌!!!
這里還發現了一個比較好用的配置參數,就是上面提到的log4j.configurationFile。
嘗試后發現:
1.如果不配或者只配置名字(log4j2.xml),就會在jar包內查找log4j2.xml
2.如果配置jar外的絕對路徑,就會在jar包外查找log4j2.xml。這個好處就是配置改動后,就不用重新打包了。
log4j2.component.properties:
1 log4j2.loggerContextFactory=org.apache.logging.log4j.core.impl.Log4jContextFactory 2 log4j.configurationFile=/home/*****/*****/config/log4j2.xml 3 #log4j.configurationFile=log4j2.xml
