How to check if log4j2 has been configured or not

六月ゝ 毕业季﹏ 提交于 2020-01-06 21:21:41

问题


We're all familiar with this message when you don't provide a configuration for log4j2:

ERROR StatusLogger No log4j2 configuration file found. Using default configuration: logging only errors to the console.

How can I check if log4j2 is not yet configured so that I can initialize with a default configuration if needed?


回答1:


I ended up creating my own ConfigurationFactory and register it with

-Dlog4j.configurationFactory

That way your ConfigurationFactory will know whether it's been invoked yet or not.




回答2:


On the first call from your app to log4j2 code, log4j will configure itself before the method returns. If no config file is found, log4j will auto-configure with a default configuration which logs only errors to the console. So from your application's point of view there is never a time that log4j is not configured.


One idea is to check if a log4j2.xml file is in the classpath (using Class.getResource), and if it isn't call System.setProperty("log4j.configurationFile", pathToYourConfig). Note that this must be done before the first call to the log4j2 API.


An alternative:

Once you have a LoggerContext you can call context.setConfigLocation(configLocation) where configLocation is a URI. That will force a reconfiguration.



来源:https://stackoverflow.com/questions/30583836/how-to-check-if-log4j2-has-been-configured-or-not

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!