简体   繁体   中英

Multiple Log4j.properties files in classpath

How does Log4j manages multiple log4j.properties in its classpath? Which log4j.properties file takes precedence? Let me describe the exact scenario.

I have multiple maven modules developed by different teams and each one of them has its own log4j.properties file. All of these log4j.properties file have RootLogger configured along with ConsoleAppender and FileAppenders.

Now, when Log4j loads which log4j.properties file will it use to configure the RootLogger settings ? Also, how will Log4j create the Logger hierarchy ? How will the log4j.properties file in other 3rd party jars affect the logging process ?

The first file in the classpath will be loaded. So if A.jar and B.jar both contain a file, and A.jar comes before B.jar in the classpath, A.jar's file will be loaded. That's how the class loader works.

log4j ver 1.x:

As others have stated, log4j looks for the first configuration file in the classpath. See: http://logging.apache.org/log4j/1.2/manual.html

But when there are both 'log4j.xml' and 'log4j.properties' files in the classpath, it seems from experimentation that log4j gives precedence to 'log4j.xml' over 'log4j.properties'.

ie First, log4j seems to look in the classpath for the first 'log4j.xml' file. If there is none, then log4j seems to then look in the classpath for the first 'log4j.properties' file.

Copying and pasting from the code below may help in determining what configuration file is being used:

import org.apache.log4j.Logger;

public class TestLog4j
{

  static
  {
    System.out.println("Classpath: [" + System.getProperty( "java.class.path" ) + "]" );
    System.out.println("Found logging configuration files:");
    System.out.println("  log4j.xml: " + Logger.getRootLogger().getClass().getResource( "/log4j.xml" ) );
    System.out.println("  log4j.properties: " + Logger.getRootLogger().getClass().getResource( "/log4j.properties" ) );
  }

  public static void main(String[] args)
  {
    System.out.println("main():");
  }
}

Edit:

log4j ver 2.x:

The search order for the default configuration file is documented here: http://logging.apache.org/log4j/2.x/manual/configuration.html

ie For log4j version 2.x, if no higher precedence configuration file is found (eg log4j2-test.[properties | yaml | json | xml]) then the file log4j2.properties is used if found in the classpath. Note that log4j2.xml has the lowest precedence, and will be used only if log4j2 'properties', 'yaml' or 'json' configuration files are all not found.

Note: To aid in debugging log4j configuration issues, set the 'log4j.debug' property, eg with:

java -Dlog4j.debug ... 

See also: How to initialize log4j properly?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM