是否有可能使log4j显示它用于配置自己的文件?

gMa*_*ale 74 java log4j

是否可以使Log4J显示其用于配置的文件的完整路径?


背景

我和log4j有一种爱恨交织的关系.在好的时候,它很棒但是当它不起作用时,它可能是最难调试的东西之一.我管理应用程序中的所有日志记录.因此,我非常熟悉日志和手册中定义默认初始化过程. 尽管如此,似乎每隔几周记录一次,我花了很多时间来解决问题.

这次,它严重受损.每个地方的每个日志语句都被转储到控制台,我无法弄清楚原因.上周使用我的log4j.xml文件的完全相同的代码库突然使用了一些其他配置.没有任何明显的变化.我唯一的猜测是,一些依赖已经改变,我怀疑Maven下载了一些破坏一切的邪恶JAR.

如果我能弄清楚Log4J决定在启动时使用哪个配置文件,我可以轻松解决这个问题和其他大多数问题.


摘要

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

mat*_*t b 77

是的,只需添加log4j.debug到JVM系统变量即可.例如:

java -Dlog4j.debug -cp ... some.class.name
Run Code Online (Sandbox Code Playgroud)

然后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".  
...
Run Code Online (Sandbox Code Playgroud)

有关参考,请参阅手册常见问题解答.

  • 出于某种原因,设置此标志对我的项目没有任何影响,可能是因为它使用SLF4J.我试图了解原因,但最后我终于手动检查了21个配置文件;) (6认同)
  • 请注意,在 log4j2 中,该属性已更改为 log4j2.debug,如果您尝试通过查找配置文件来调试问题,您可能还需要设置 -Dorg.apache.logging.log4j.simplelog.StatusLogger.level=TRACE。 (2认同)

Ben*_*Ben 7

我正在使用 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());
Run Code Online (Sandbox Code Playgroud)