I have a common jar that multiple web applications are using. All the web applications are using log4j. Each has their own log4j xml configuration file that are basically the same. I would like to put a common log4j configuration in the included jar file and in each individual web project, in that log4j configuration, I would like to be able to simply refer to the one in the jar file.
I’m not seeing anything in the documentation that explicitly says this is possible. I’m wondering if I might just remove the configuration file from the web projects and stick it in the common jar if it would get loaded automatically since it is on the class path?
In the end, I would like the ability to adjust logging on a particular application for debugging and troubleshooting without modifying the common configuration in the jar file.
I was on a project where I needed to manage dozens of web applications. Each of the apps were logging slightly differently and it was a pretty big pain to manage. I used a strategy similar to what you are describing to standardize on log4j and it has worked out pretty well.
Basically, I created a single common.jar which contains shared code. This jar contains a log4j.xml that sets log level to INFO and sets the default appender to stdout for common.jar. This log4j config is used as the baseline for all other apps.
For this example, pretend this class is inside common.jar:
Now, all other web applications can simply depend on common.jar. For example, pretend this class is inside myapp.war:
Since log4j.xml is inside common.jar, this code will log something like this. In other words, there’s no need to put log4j.xml inside myapp.war:
Now, if you want/need to control logging in myapp.war, then simply place a log4j.xml inside myapp.war and override settings from common.jar. For example, you might set the level to DEBUG, and then you’ll see:
UPDATE – Is it possible to configure each webapp to log to separate file?
Yes, definitely. For example, you can direct logs to a RollingFileAppender instead of stdout inside log4j.xml for myapp.war. This is handy because then you can have each individual webapp log to it’s own separate file.
In addition, I wrote a servlet filter (similar to what gigadot suggested) which configures log4j to check for whether a log4j.xml exists at an external path (outside of each webapp’s war). This way, the log4j.xml files are accessible outside the wars and we’re able to set log levels without restarting the servlet container (tomcat, in this case). If the external log4j.xml doesn’t exist, it defaults to use the log4j.xml on each apps classpath.