在普通web项目中,可以书写如下xml配置文件:
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE log4j:configuration SYSTEM "log4j.dtd"> <log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/"> <appender name="file.log" class="org.apache.log4j.RollingFileAppender"> <!-- 这里必须用绝对路径(或相对于tomcat的路径) --> <param name="File" value="c:\logs\myweb.log" /> <param name="Append" value="false" /> <layout class="org.apache.log4j.PatternLayout"> <param name="ConversionPattern" value="%-d{yyyy-MM-dd HH:mm:ss} [%C:%M()]-[%p] %m%n" /> </layout> </appender> <appender name="console.log" class="org.apache.log4j.ConsoleAppender"> <layout class="org.apache.log4j.PatternLayout"> <param name="ConversionPattern" value="%5p (%F:%L) - %m%n" /> </layout> </appender> <!--这里的name是要打印的包名,这里表示将org.woden模块中(包括子模块)的中间信息全部打印--> <logger name="org.woden" additivity="false"> <level value="DEBUG" /> <appender-ref ref="console.log" /> <appender-ref ref="file.log " /> </logger> <!--这里root配置成fatal级别是防止打印出框架中的中间信息(解决了打印struts中间信息的问题)--> <root> <level value="FATAL" /> <appender-ref ref="console.log" /> <appender-ref ref="file.log " /> </root> </log4j:configuration>
然后自己写一个Servlet,命名为Log4jInit,代码如下:
package org.woden.controller.servlet;
import java.io.IOException;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.xml.DOMConfigurator;
public class Log4jInit extends HttpServlet {
public void init(ServletConfig config) throws ServletException {
super.init(config);
String prefix = getServletContext().getRealPath("/");
String file = getInitParameter("log4j");
System.out.println("-------- Log4J Start --------- ");
if (file != null) {
DOMConfigurator.configure(prefix + file);
}
}
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
}
}
然后在web.xml中配置Servlet启动:
<servlet> <servlet-name>MyLog4jInit</servlet-name> <servlet-class>org.woden.controller.servlet.Log4jInit</servlet-class> <init-param> <param-name>log4j</param-name> <param-value>WEB-INF/log4j.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet>
注意:启动级别最好设小点,表示更快启动.一些IDE一般把struts(Action)启动级别设成了3或2,最好把log4j的启动放到struts之前.
另外,在spring框架中对log4j进行了增强:
首先不需要自己写servlet来启动log4j,而是直接用spring的Log4jConfigListener监听器.这样做有几个好处,最大的好处就是不用重启web应用也可以改变log4j的级别(和策略).而且spring允许将log文件放到项目的相对目录中.
spring中在web.xml的配置语句如下:
<context-param> <param-name>log4jConfigLocation</param-name> <param-value>WEB-INF/log4j.xml</param-value> </context-param> <context-param> <param-name>log4jRefreshInterval</param-name> <param-value>60000</param-value><!--60秒扫描一次--> </context-param> <listener> <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class> </listener>
在log4j的配置文件中,进行相应修改:
<!--将log文件放到项目相对目录中-->
<param name="File" value="${webapp.root}/WEB-INF/logs/test.log " />