是否可以让 log4j 显示它用来配置自己的文件?

提问

有没有可能让 Log4J 显示它用于配置的文件的完整路径?


背景资料

我对 log4j 又爱又恨。在好的时候,它是很棒的,但是当它不工作的时候,它可能是最难调试的东西之一。我管理应用程序中的所有日志记录。因此,我非常熟悉日志和 手册中定义的默认初始化过程。仍然,似乎,每隔几个星期,日志休息,我花了 很多的时间来解决这个问题。

这次伤得很重。所有地方的每一条日志语句都被转储到控制台,我不知道为什么。上周使用 log4j.xml 文件的代码库突然使用了其他一些配置。一切都没有明显改变。我唯一的猜测是,一些依赖关系已经改变,我怀疑 Maven 已经下载了一些破坏一切的邪恶 JAR。

如果我能算出 Log4J 决定在启动时使用哪个配置文件 ,我就可以很容易地解决这个问题和大多数其他问题。


摘要

有什么方法可以告诉 Log4J 打印它用于配置的文件吗?或者,是否有办法中断正在运行的应用程序并使用调试器来回答这个问题(可能使用表达式或通过检查变量) ?

36317 次浏览

Yes, simply add log4j.debug to the JVM system variables. For example:

java -Dlog4j.debug -cp ... some.class.name

Log4j will then output something like the following:

log4j: Trying to find [log4j.xml] using context classloader sun.misc.Launcher$AppClassLoader@1f7182c1.
log4j: Using URL [file:/C:/Users/matt/workspace/projectname/target/test-classes/log4j.xml] for automatic log4j configuration.
log4j: Preferred configurator class: org.apache.log4j.xml.DOMConfigurator
log4j: System property is :null
log4j: Standard DocumentBuilderFactory search succeded.
log4j: DocumentBuilderFactory is: org.apache.xerces.jaxp.DocumentBuilderFactoryImpl
log4j: debug attribute= "null".
log4j: Ignoring debug attribute.
log4j: reset attribute= "false".
log4j: Threshold ="null".
...

For reference see the manual and the FAQ.

I am using Log4J2 and if you want to get the file from inside your Java Program this worked for me:

LoggerContext lContect = LogManager.getContext();
Field f = lContect.getClass().getDeclaredField("configuration");
f.setAccessible(true);
XmlConfiguration iWantThis = (XmlConfiguration) f.get(lContect);
System.out.println("Config File: " + iWantThis.getName());

The log4j 2 equivalent for this is to set <Configuration status="trace"> in the configuration file. This will display the location from where the log4j2 configuration file is loaded, as well as other internal details of the log4j2 configuration process. By default the status logger level is WARN, so you only see notifications when there is a problem.

If the configuration file is not found correctly, you can still enable log4j2 internal status logging by setting system property org.apache.logging.log4j.simplelog.StatusLogger.level to TRACE.