Showing posts with label java webapp jar url log4j properties inside servlet. Show all posts
Showing posts with label java webapp jar url log4j properties inside servlet. Show all posts

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.