从Log4j切换到Log4j2,没有打包以前日志输出正常,可是打包后老是提示下面内容:html
错误一:apache
ERROR StatusLogger Log4j2 could not find a logging implementation. Please add log4j-core to the classpath. Using SimpleLogger to log to the console...spa
错误二:日志
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.
被这个问题折腾了一天多,总算是找到一个解决办法,在这里记录一下。code
错误一:component
网上有人说是没有导入log4j-core,可是导入后仍是出现这个错误。xml
有人说log4j2有个加载配置文件的顺序(https://logging.apache.org/log4j/2.x/manual/configuration.html),因此试了各类名字,仍是失败。htm
这里还尝试了添加启动参数(-Dlog4j.configurationFile=log4j2.xml),以及在src下添加log4j2.component.properties文件(内容:log4j.configurationFile=log4j2.xml),结果一样失败。blog
错误二:it
这个问题在网上没有多少能够参考的信息,可是在解决错误一时,看到有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