是否有可能让log4j显示它用来configuration自己的文件?

是否有可能使Log4J显示它用于configuration的文件的完整path?


背景

我对log4j有一种爱与恨的关系。 在好的时候,这很好,但是当它不工作时,它可能是最难debugging的事情之一。 我pipe理我们应用程序中的所有日志。 因此,我非常熟悉手册中定义的日志logging和默认初始化过程。 不过,似乎每隔几个星期,伐木就会中断,我花了很多时间来解决问题。

这一次,这是严重破碎。 每一个日志声明无处不在被转储到控制台,我不明白为什么。 上周使用我的log4j.xml文件的相同的代码基础突然使用其他configuration。 没有什么明显的变化。 我唯一的猜测是,一些依赖已经改变了,我怀疑Maven已经下载了一些破坏所有东西的邪恶JAR。

如果我能找出Log4J在启动时决定使用哪个configuration文件 ,我可以轻松解决这个问题和其他大多数问题。


概要

有没有办法告诉Log4J打印哪个文件用于configuration? 另外,有没有办法打破正在运行的应用程序,并使用debugging器来回答这个问题(也许用expression式或通过检查variables)?

是的,只需将log4j.debug添加到JVM系统variables即可。 例如:

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

Log4j然后会输出如下内容:

 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". ... 

参考手册和FAQ 。

我正在使用Log4J2,如果你想从你的Java程序中得到这个文件,这为我工作:

 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()); 

log4j 2的等价物是在configuration文件中设置<Configuration status="trace"> 。 这将显示加载log4j2configuration文件的位置,以及log4j2configuration过程的其他内部细节。 默认情况下,状态logging器级别是WARN,所以只有在出现问题时才能看到通知。

如果configuration文件找不到,仍然可以通过将系统属性org.apache.logging.log4j.simplelog.StatusLogger.level设置为TRACE来启用log4j2内部状态logging。