问题
I am using Apache Jackrabbit as a content repository for a couple of web applications deployed to a single tomcat container. To get jackrabbit as a jndi resource I have added the jackrabbit jar and all it's dependencies (which includes slf4j and log4j) in tomcat/lib to make it available to all my web apps. However there is a problem with logging...
On start up log4j complains that there are no appends found:
log4j:WARN No appenders could be found for logger (org.apache.jackrabbit.core.config.ConfigurationErrorHandler).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
Now neither jackrabbit nor my web applications produce any logging statements.
I tried adding a log4j.xml config to the lib directory, no go. Also tried adding it directly in the jackrabbit jar with no luck.
How can I configure log4j for a dependency in the tomcat/lib as well as for each web application in tomcat?
回答1:
From the log4j warning it is very clear that in your application log4j is not initialized, I am not sure earlier how you was doing in your application but for now you can try this. I have used the same approach in my appication where all the logging jars was present in server lib directory.
- Put the log4j.properties in your project WEB-INF directory and ask your servlet to initialize it during the application startup time. You can write a start up servlet and in the init method you can pass this properties file to the init as params.
e.g : in your web.xml something like this.
<servlet>
<servlet-name>MyLog4JInitServlet</servlet-name>
<servlet-class>test.MyLog4JInitServlet</servlet-class>
<init-param>
<param-name>log4j-properties-location</param-name>
<param-value>WEB-INF/log4j.properties</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
And you can have init method in your servlet like this to initialize log4j.
public void init(ServletConfig config) throws ServletException {
String log4jLocation = config.getInitParameter("log4j-properties-location");
ServletContext sc = config.getServletContext();
if (log4jLocation == null) {
BasicConfigurator.configure();
} else {
String webAppPath = sc.getRealPath("/");
String log4jProp = webAppPath + log4jLocation;
File logFile= new File(log4jProp);
if (logFile.exists()) {
System.out.println("Initializing log4j with: " + log4jProp);
PropertyConfigurator.configure(log4jProp);
} else {
System.err.println("*** " + log4jProp + " file not found, so initializing log4j with BasicConfigurator");
BasicConfigurator.configure();
}
}
super.init(config);
}
Cheers
来源:https://stackoverflow.com/questions/17888360/log4j-in-tomcat-lib-and-in-each-webapp