How can I tell where is Log4j picking its configuration from

僤鯓⒐⒋嵵緔 提交于 2019-12-05 18:35:00

When running your application you can set the system property -Dlog4j.debug. log4j will produce debug output in this case and tells you about how it resolves the path to the log4j.xml, e.g.:

log4j: Trying to find [log4j.xml] using context classloader sun.misc.Launcher$AppClassLoader@11b86e7.
log4j: Using URL [file:/C:/develop/workspace/foobar/target/classes/log4j.xml] for automatic log4j configuration.
log4j: Preferred configurator class: org.apache.log4j.xml.DOMConfigurator

To set a path explicit use the system property -Dlog4j.configuration=file:c:/pathToFile as described here.

Tim Büthe

Activating -Dlog4j.debug like suggested by FrVaBe in his answer is a good solution. However, I wanted to print or log the location on startup without activating log4j's debug mode. I created a little util method, that is mostly a copy of log4j's default init routine, which returns the URL of the configuration file.

Maybe it's useful for someone else:

/**
 * Get the URL of the log4j config file. This is mostly copied from org.apache.log4j.LogManager's default init routine.
 *
 * @return log4j config url
 */
public static URL getLog4JConfigurationUrl(){

    /** Search for the properties file log4j.properties in the CLASSPATH.  */
    String override = OptionConverter.getSystemProperty(LogManager.DEFAULT_INIT_OVERRIDE_KEY, null);

    // 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)){

      String configurationOptionStr = OptionConverter.getSystemProperty(LogManager.DEFAULT_CONFIGURATION_KEY, null);

      URL url;

      // if the user has not specified the log4j.configuration
      // property, we search first for the file "log4j.xml" and then
      // "log4j.properties"
      if (configurationOptionStr == null){
        url = Loader.getResource("log4j.xml");
        if (url == null){
          url = Loader.getResource(LogManager.DEFAULT_CONFIGURATION_FILE);
        }
      } else {
        try {
          url = new URL(configurationOptionStr);
        } catch (MalformedURLException ex) {
          // so, resource is not a URL:
          // attempt to get the resource from the class path
          url = Loader.getResource(configurationOptionStr);
        }
      }

      if (url == null)
        throw new RuntimeException("log4j configuration could not be found!");

      return url;
    }

    throw new RuntimeException("default init is overridden, log4j configuration could not be found!");
  }

PS: if you know a way to ask log4j for it's currently used configuration file, let me know.

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