Tuesday, March 23, 2010

Load log4j.properties from jar file in webapp

Having environment specific log4j.properties inside a jar file is hardly an ideal solution, but if you find yourself in a similar situation:



import java.net.URL;
import org.apache.log4j.PropertyConfigurator;
import javax.servlet.http.HttpServlet;

public class Log4jConfLoad extends HttpServlet {

@Override
public void init() {
try {
String prefix = "jar:file:" + getServletContext().getRealPath("/");
String path = "WEB-INF/lib/the.jar!/" + System.getProperty("env") + "/log4j.properties";
PropertyConfigurator.configure(new URL(prefix+path));
catch (Exception ex) {
//Because Servlet init can't be declared as throwing new exception.
//Any thrown Exception here should show up in catalina.out (if Tomcat used)
throw new RuntimeException(ex);
}
}
}


Also remember to add the servlet to web.xml with load-on-startup.

1 comment:

Alex Ooi said...

perhaps putting the configuration code in a ServletContextListener, instead of the init() method of a Servlet, might be more appropriate?

The point of a ServletContextListener is to listen to the initialization and destruction of the web apps context. This seems to suggest that it makes more sense to do stuff like 'bootstrapping' work in here rather than an actual servlet, even tho I'm sure that in the end the result is the same ....