Configuring context-specific logging
At iPROFS, we have developed a certain habit when it comes to logging configurations.
This originates from certain clients who demand that deployable applications consist of
- the application artifacts (wars, ears)
- environment-specific configuration files
Being able to provide environment-specific configuration files, enables us also to create environment-specific logging configurations:
acceptance and production environment log at WARN level, test environment at INFO, development environment at DEBUG.
That’s fine, but how do you configure the logging provider per webapp, from a configuration file that’s external to the application?
Because that is what you need (unless you’re fine with creating multiple wars/ears with only a different configuration file set)
Log4j
For Log4j, JBoss already suggests a custom RepositorySelector.
This RepositorySelector lets every context class loader have its own configuration set up with its own log4j.xml file. This solution is targeted at putting the log4j.xml into WEB-INF/classes or whatever.
This is a fine starting point, however it’s still not external to the application.
So at iPROFS we normally use a slightly different version of this RepositorySelector, which looks for a <context-name>-log4j.xml file anywhere on the classpath. Now we can put the log4j configuration files in some external location.
This works great for Log4J.
Logback
Now enter Logback, the successor of Log4J, and a great default implementation of SLF4J.
Logback put quite some effort into documenting some possible setups for achieving per-context logging, but none looks like the Log4J repository selector described above.
So we rolled our own.
Solution
The ClasspathContextLogbackConfigurator we created, looks for a configuration file <context-name>-logback.xml on the classpath, just like the Log4J solution above. It feeds this configuration file to a basic logback configurator, and you’re set.
Combine this with the autoscan feature of Logback and you’ve got a environment-specific, runtime tunable Logback configuration.
To get you up to speed, I put the classes into a mavenized artifact.
This can be included into your webapp as a dependency:
<dependency> <groupId>nl.iprofs.modules.context-logging</groupId> <artifactId>context-logging</artifactId> <version>1.0.2</version> </dependency>
Check out the source to adapt things to your needs.
Some final thoughts:
- All webapps should ship their own log4j/logback jars, preventing them from all configuring the same logger instance from the parent classloader
- where “on the classpath” is, is not discussed here. In Tomcat you could specify a custom directory to be added to the classpath, in
$CATALINA_BASE/conf/catalina.properties, with the property ‘common.loader’
Recent Comments