1.Some tools
Tomcat
Log4j_1.2.9 http://mirrors.xtria.com/apache/logging/log4j/1.2.9/logging-log4j-1.2.9.zip
2. four files
a. web.xml
add following code to web.xml
<servlet>
<servlet-name>log4j-init</servlet-name>
<servlet-class>com.legendinfo.log.Log4jInit</servlet-class>
<init-param>
<param-name>log4j-init-file</param-name>
<param-value>WEB-INF/classes/log4j.property</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
b.create a special servlet for log4j initialazation
save the file in the web-info/classes folder
package com.legendinfo.log;
import org.apache.log4j.PropertyConfigurator;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.io.IOException;
public class Log4jInit extends HttpServlet {
public void init() {
String prefix = getServletContext().getRealPath("/");
String file = getInitParameter("log4j-init-file");
// if the log4j-init-file is not set, then no point in trying
if(file != null) {
PropertyConfigurator.configure(prefix+file);
System.out.println("Init Log4j success!");
}
}
public void doGet(HttpServletRequest req, HttpServletResponse res) {
}
}
c.create a log4j.property file that define the log4j properties
the property file is setting in web.xml
a sample property file as following
log4j.rootLogger=INFO, A1 ,R
log4j.appender.A1=org.apache.log4j.ConsoleAppender
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=%-d{yyyy-MM-dd HH:mm:ss} [%c]-[%p] %m%n
log4j.appender.R=org.apache.log4j.RollingFileAppender
log4j.appender.R.File=../logs/log4j.log
log4j.appender.R.MaxFileSize=100KB
log4j.appender.R.MaxBackupIndex=1
log4j.appender.R.layout=org.apache.log4j.TTCCLayout
d.a test Jsp page
testLog.jsp:
<%@ page import="org.apache.log4j.*"%>
<html>
<body>
<%
//log4j.appender.appenderName = WEB-INF/classes/log4j.log
Logger logger = Logger.getLogger("com.legendinfo");
logger.setLevel(Level.INFO);
Logger barlogger = Logger.getLogger("com.legendinfo.log");
logger.warn("Low fuel level.");
logger.debug("Starting search for nearest gas station.");
barlogger.info("Located nearest gas station.");
barlogger.debug("Exiting gas station search");
%>
</body>
</html>
3. resault
after you startup your tomcat , you can see the success log “Init Log4j success!“
and you can look the testLog.jsp then the logs will be found in the tomcat log file and log/log4j.log file
4.some feedback please send to http://blog.csdn.net/legendinfo or jiujiul@126.com