1.LOG4J的配置:采用log4j.properties文件

log4j.rootCategory=warn,A1
log4j.appender.A1=org.apache.log4j.DailyRollingFileAppender

#log4j.appender.A1=org.apache.log4j.RollingFileAppender
log4j.appender.A1.File=F:/tmp/sogoudoc.txt
#log4j.appender.A1.MaxFileSize=1024KB
#log4j.appender.A1.MaxBackupIndex=1
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=%-5p: %c{2}  %d{yyyy-MM-dd HH:mm:ss} %m%n


log4j.logger.log=debug

2.LOG4J的初始化:用一个Servlet来实现它的初始化

package servlet;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

import org.apache.log4j.PropertyConfigurator;

public class Log4jInit extends HttpServlet
{
 public void init() throws ServletException
 { 
  // 从Servlet参数读取log4j的配置文件
  PropertyConfigurator.configure(Log4jInit.class.getResource("log4j.properties"));
 }

 public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
 {
 }

 public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
 {
 }
}

 web.xml中增加:

<servlet>
  <servlet-name>Log4jInit</servlet-name>
  <servlet-class>servlet.Log4jInit</servlet-class>
  <init-param>
   <param-name>log4j-config-file</param-name>
   <param-value>log4j.properties</param-value>
  </init-param>
  <load-on-startup>1</load-on-startup>

 </servlet>

3.使用LOG4J:

package log;

import org.apache.log4j.*;

public class Log
{
 
 private Logger log = Logger.getLogger(Log.class);
 
 public void testLog()
 {
  try
  {
   log.info("info test");
   log.warn("warn test");
  }
  catch (Exception e)
  {
   e.printStackTrace();
  }
 }
 
}