Skip to content
Advertisement

Can I skip/omit a log4j2 configurationFile that doesn’t exist to fall back to an existing one?

I am running log4j2 logging in a java application with not the most flexibility in setup. We have an existing log4j2.xml configuration file in the classpath of our application that exists within an executable jar. I can modify the jar but not what calls it or is outside of it (I don’t control the environment). I would like to add an optional overriding log4j2 configuration file outside of the jar. When it exists it overrides log4j2.xml, when it doesn’t log4j2.xml is used. So I added this property to a log4j2.component.properties file:

log4j.configurationFile=../conf/log4j2-override.xml

When I create this optional file it works perfectly. When I don’t create this file, log4j2 prints an error that the file cannot be found and then fails to fallback to the existing log4j2.xml file in the classpath. It doesn’t seem to matter if I add the classpath-specific file to the configurationFile property. The configuration file is certainly available because if I remove the property completely it uses the configuration from the jar’s classpath.

It’s seems log4j2 has an error looking for the file and stops the automatic configuration sequence instead of continuing. Is there anyway for me to optionally override the default configuration xml file without requiring it be present outside the jar if I choose not to? I am hoping to specify this from within the jar file instead of requiring the way in which the jar is called to be changed based on the files existence.

Advertisement

Answer

The log4j.configurationFile property allows you to specify a comma-separated list of configuration sources, which will be merged using a merge strategy (see DefaultMergeStrategy for the default rules). In your case you can use:

log4j.configurationFile=classpath:log4j2.xml,../conf/log4j2-override.cml

Missing files will be ignored and a warning will be sent to the status logger.

Log4j 2.13.x is affected by bug LOG4J2-2901, which stops the configuration process if a file is missing. Therefore make sure to use the latest version.

Advertisement