pom.xml中添加依赖。
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
maven会自动添加相应的jar包
配置log4j初始化用的servlet
web.xml中添加下面servlet
<servlet>
<servlet-name>log4j-init</servlet-name>
<servlet-class>com.suyang.servlet.Log4jInit</servlet-class>
<init-param>
<param-name>log4j-init-file</param-name>
<param-value>\WEB-INF\classes\log4j.properties</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
添加对应的servlet
Log4jInit.java
package com.suyang.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.PropertyConfigurator;
/**
* Servlet implementation class Log4jInit
*/
public class Log4jInit extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
// TODO Auto-generated method stub
super.doGet(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
// TODO Auto-generated method stub
super.doPost(req, resp);
}
@Override
public void init() throws ServletException {
// TODO Auto-generated method stub
super.init();
String prefix = getServletContext().getRealPath("/");
String file = getInitParameter("log4j-init-file");
if (file != null) {
System.out.println("read log4j.properties:"+prefix + file);
PropertyConfigurator.configure(prefix + file);
}
}
}
在resources中添加log4j.properties文件,maven会自动把文件复制到classes目录下
log4j.rootLogger = DEBUG , stdout , D
log4j.appender.stdout = org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target = System.out
log4j.appender.stdout.layout = org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n
log4j.appender.D = org.apache.log4j.DailyRollingFileAppender
log4j.appender.D.Threshold= DEBUG
log4j.appender.D.File= ${catalina.home}/logs/log.log
log4j.appender.D.ImmediateFlush= true
log4j.appender.D.Append= true
log4j.appender.D.DatePattern='-'yyyy-MM-dd-HH'.log'
log4j.appender.D.Encoding= UTF-8
log4j.appender.D.layout= org.apache.log4j.PatternLayout
log4j.appender.D.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n
日志会自动记录DEBUG级别以上的日志。