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.
3 comments:
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 ....
Having environment specific log4j.properties inside a jar file is hardly an ideal solution, but if you find yourself in a similar situation:
wholesale shawls , wholesale pashmina , pashmina shawl wholesale , pashminas in bulk , wholesale scarves in bulk , wholesale scarf suppliers , chiffon scarves wholesale , wholesale prayer shawls , velvet shawls wholesale , velvet shawl
This single-liner worked OK:
PropertyConfigurator.configure(getClass().getResourceAsStream("/log4j.properties"));
Just include the properties file on the root of the resource folder.
Post a Comment