gpt4 book ai didi

java - 如何找到 log4j 默认初始化中使用的 URL?

转载 作者:搜寻专家 更新时间:2023-11-01 01:13:46 25 4
gpt4 key购买 nike

Log4j default initialization通过一个过程来查找和使用 URL 进行配置。之后,您如何才能找出最终使用的 URL,而不必自己编写相同的程序? (如果您必须自己编写代码,您可能无法获得与 log4j 完全相同的效果,而且它可能会在未来的版本中发生变化。)

最佳答案

如果你愿意使用AspectJ LTW(load-time weaving),你可以看看Ian Roberts提到的LogManager的静态初始化。在 log4j 1.2.14 中,它看起来像这样:

static {
// (...)
// if there is no default init override, then get the resource
// specified by the user or the default config file.
if (override == null || "false".equalsIgnoreCase(override)) {
// (...)
URL url = null;

// (...)
// If we have a non-null url, then delegate the rest of the
// configuration to the OptionConverter.selectAndConfigure method.
if (url != null) {
LogLog.debug("Using URL [" + url + "] for automatic log4j configuration.");
OptionConverter.selectAndConfigure(
url, configuratorClassName, LogManager.getLoggerRepository()
);
} else {
LogLog.debug("Could not find resource: [" + configurationOptionStr + "].");
}
}
}

显然,如果可以确定默认 URL,则将在静态 block 中的某一点调用 OptionConverter.selectAndConfigure(URL, ..) 以初始化 log4j使用该 URL。

通过 AspectJ 捕获该方法调用非常简单:

import java.net.URL;
import org.apache.log4j.helpers.OptionConverter;
import org.apache.log4j.LogManager;

public aspect Log4jAspect {
before(URL defaultURL) :
within(LogManager) &&
cflow(staticinitialization(LogManager)) &&
call(* OptionConverter.selectAndConfigure(URL, ..)) &&
args(defaultURL, ..)
{
System.out.println("log4j default URL = " + defaultURL);
}
}

这段代码的意思是:

  • 如果我们在 LogManager 类中并且
  • 在静态类初始化的控制流中
  • OptionConverter.selectAndConfigure被调用,
  • 然后捕获第一个参数(URL)和
  • 将其打印到控制台(您也可以做其他事情)。

如果没有默认 URL,则不会打印任何内容。您可以将其分配给任何类或任何您喜欢的静态成员,而不是打印 URL。

这是针对您的问题的解决方案,我对其进行了测试并且有效。我很高兴收到回答您问题的赏金,即使该解决方案可能使用了您没有想到的技术。但它解决了这个问题。 :-)


编辑: 在没有找到默认 URL 的情况下,也可以显式拦截日志调用,尽管我认为没有必要。我只是想提一下。

关于java - 如何找到 log4j 默认初始化中使用的 URL?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12162423/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com