编辑servlet:
1package my.scwcd;
2
3
4import javax.servlet.ServletException;
5import javax.servlet.http.HttpServlet;
6
7import org.apache.log4j.PropertyConfigurator;
8
9public class Log4jInit extends HttpServlet {
10
11 public Log4jInit() {
12 super();
13 }
14
15 public void destroy() {
16 super.destroy(); // Just puts "destroy" string in log
17 }
18
19 public void init() throws ServletException {
20 String path = getServletContext().getRealPath("/");
21
22 String file = getInitParameter("log4j");
23 if(file != null){
24 PropertyConfigurator.configure(path+file);
25 }
26
27 }
28
29}
30
31
1 <servlet>
2 <servlet-name>Log4jInit</servlet-name>
3 <servlet-class>my.scwcd.Log4jInit</servlet-class>
4 <init-param>
5 <param-name>log4j</param-name>
6 <param-value>WEB-INF\log4j.properties</param-value>
7 </init-param>
8 <load-on-startup>1</load-on-startup>
9 </servlet>
10
还有加上log4j.properties文件在WEB-INF目录下
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%nlog4j.appender.R=org.apache.log4j.RollingFileAppender
log4j.appender.R.File=log4j.log
log4j.appender.R.MaxFileSize=100KB
log4j.appender.R.MaxBackupIndex=1
log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern=%p %t %c - %m%n下面写了两个测试的程序:
servlet Test.java中:
1 public void doGet(HttpServletRequest request, HttpServletResponse response)
2 throws ServletException, IOException {
3
4 response.setContentType("text/html");
5 PrintWriter out = response.getWriter();
6 Logger logger = Logger.getLogger(Test.class);
7 logger.info("Test use Logging for Servlet");
8 out.println("<h1>Success<h1>");
9 out.flush();
10 out.close();
11 }
12
13JSP temp.jsp中:1 <%
2 response.setContentType("text/html");
3 Logger logger = Logger.getLogger("temp.jsp");
4 logger.info("Test use Logging for JSP");
5 out.println("<h1>Success<h1>");
6 %>
7这样在%TOMCAT_HOME%\bin目录下会产生log4j.log的文件,这就是日志文件。