pom.xml中添加依赖。
maven会自动添加相应的jar包log4j log4j 1.2.17
配置log4j初始化用的servlet
web.xml中添加下面servlet
添加对应的servletlog4j-init com.suyang.servlet.Log4jInit log4j-init-file \WEB-INF\classes\log4j.properties 1
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 , Dlog4j.appender.stdout = org.apache.log4j.ConsoleAppenderlog4j.appender.stdout.Target = System.outlog4j.appender.stdout.layout = org.apache.log4j.PatternLayoutlog4j.appender.stdout.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%nlog4j.appender.D = org.apache.log4j.DailyRollingFileAppenderlog4j.appender.D.Threshold= DEBUGlog4j.appender.D.File= ${catalina.home}/logs/log.loglog4j.appender.D.ImmediateFlush= truelog4j.appender.D.Append= truelog4j.appender.D.DatePattern='-'yyyy-MM-dd-HH'.log'log4j.appender.D.Encoding= UTF-8log4j.appender.D.layout= org.apache.log4j.PatternLayoutlog4j.appender.D.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n日志会自动记录DEBUG级别以上的日志。