How to use multiple configuration files for log4j2

user3093295 picture user3093295 · Apr 21, 2014 · Viewed 12.9k times · Source

I am writing Java code that tests a Java library. The library includes its own log4j2 configuration as part of the distribution.

I would like to use log4j2 in my test code without modifying the library's configuration.

Is there a way to have a separate log4j2 configuration for my test code?

This is all running as command-line Java, no servers or web involvement at all.

EDIT to try to be more clear: What I want is to be able to configure loggers, appenders, etc for the test code to use , and at the same time have the library code use its own separate configuration file for its logging. The idea is to use log4j2 in my test code, but without having to change the library's configuration file. Since the library configuration file is part of the library's distribution, I don't want to change it for testing.

Answer

Remko Popma picture Remko Popma · Apr 22, 2014

This may be helpful:

  • Log4j2 will first look for log4j2-test.xml in the classpath
  • if that file is not found, it will look for log4j2.xml in the classpath

So one option is to copy the library's configuration (log4j2.xml) to log4j2-test.xml and add your own configuration to log4j2-test.xml.

Furthermore, Log4j2 supports XInclude in XML configuration, so you could use that feature to avoid duplicating the library's configuration in your log4j2-test.xml.