log4j的使用步骤2011-02-121、首先将log4j-1.2.8.jar包含入类路径中。2、Log4J必须在应用的其它代码执行前完成初始化。其初始化内容如下:
import java.io.*;import javax.servlet.*;import org.apache.log4j.*;public class Log4JInit extends HttpServlet {public void init() throws ServletException {String prefix = getServletContext().getRealPath("/");String file = getServletConfig().getInitParameter("log4j-config-file");// 从Servlet参数读取log4j的配置文件if (file != null) {PropertyConfigurator.configure(prefix + file);}}public void doGet(HttpServletRequest request,HttpServletResponse response)throwsIOException, ServletException {}public void doPost(HttpServletRequest request,HttpServletResponse response)throwsIOException, ServletException {}}3、web.xml内容配置如下:具体的文件放在 路径:webapps项目名称WEB-INFweb.xml
<?xml version="1.0" encoding="ISO-8859-1"?><!DOCTYPE web-appPUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN""http://java.sun.com/dtd/web-app_2_3.dtd"><web-app><servlet><servlet-name>log4jinit</servlet-name><servlet-class>com.iss.common.util.Log4JInit</servlet-class>//这里换换成具体的初始化文件包<init-param><param-name>log4j-config-file</param-name><param-value>WEB-INFlog4j.properties</param-value></init-param><load-on-startup>1</load-on-startup></servlet>< type="text/javascript"><!-- Establish the default list of welcome files --><welcome-file-list><welcome-file>index.jsp</welcome-file><welcome-file>index.html</welcome-file><welcome-file>index.htm</welcome-file></welcome-file-list><error-page><error-code>404</error-code><location>/FileNoFound.jsp</location></error-page></web-app>
注意:上面的load-on-startup应设为1,以便在Web容器启动时即装入该Servlet。log4j.properties文件放在根的properties子目录中,也可以把它放在其它目录中。应该把.properties文件集中存放,这样方便管理。