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.
Configuration of Log4j 2 can be accomplished in 1 of 4 ways: Through a configuration file written in XML, JSON, YAML, or properties format. Programmatically, by creating a ConfigurationFactory and Configuration implementation.
Use LogManager. resetConfiguration(); to clear the current config and configure it again. Another approach is to build a new appender and replace the old one with it (most appenders don't support changing their config).
We should put log4j2. xml anywhere in the application's classpath. Log4j will scan all classpath locations to find out this file and then load it. We can find this file mostly placed in the 'src/main/resources' folder.
This may be helpful:
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.
Log4j2 supports "Composite Configuration" which exactly matches your requirement. All you need to do is provide path to multiple files in log4j.configurationFile
property. This can be passed from command line or added to log4j2.component.properties
file in your application.
References: https://logging.apache.org/log4j/2.x/manual/configuration.html#CompositeConfiguration https://logging.apache.org/log4j/2.x/manual/configuration.html#SystemProperties
There are two step you can try to solve for your issue
cmd> java -Dlog4j.configuration=location/xyz.properties
If you use diffent name for configuration rather log4j.properties/.xml file you need to configure that file at runtime by above command for more info have a look here..
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With