最详细的log4j教程 https://blog.csdn.net/u013870094/article/details/79518028

Log4j与J2ee结合

2.1 使用spring架构
Spring真是不错,替我们做了很多事情,如果系统使用了spring框架,则要集成log4j就很简单了,主要分为3个步骤,如下:

2.1.1 定义log4j配置文件

复制代码代码如下:

log4j.rootCategory=INFO, stdout
log4j.rootLogger=info, stdout

stdout

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{ABSOLUTE} %5p - %m%n

log to file

log4j.logger.org.springframework=info
log4j.logger.org.apache.catalina=info
log4j.logger.org.apache.commons.digester.Digester=info
log4j.logger.org.apache.catalina.startup.TldConfig=info
log4j.logger.chb.test=debug

2.1.2 定义监听器
监听器需要定义在web.xml,主要包括:定义log4j配置文件目录、log4j监听器,如下:

复制代码代码如下:


xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">;



   log4jConfigLocation
   /WEB-INF/log4j.properties



   contextConfigLocation
   
       /WEB-INF/classes/applicationContext*.xml
   




   
       org.springframework.web.util.Log4jConfigListener
   



   
       org.springframework.web.context.ContextLoaderListener
   



   InitiaServlet
chb.test.web.InitiaServlet
   1


index.jsp

2.1.3 测试类

复制代码代码如下:

package com.dheaven.mip.web;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;

import org.apache.log4j.Logger;

public class InitiaServlet extends HttpServlet {

protected Logger log = Logger.getLogger(InitiaServlet.class);

private static final long serialVersionUID = 8550329576989690578L;

/**
 * Constructor of the object.
 */
public InitiaServlet() {
   super();
}

/**
 * Destruction of the servlet. 
*/ public void destroy() { super.destroy(); } /** * Initialization of the servlet.
* * @throws ServletException if an error occure */ public void init() throws ServletException { log.debug("服务器启动了,log4j开始工作了"); }

}