1。使用log4j必须在服务器启动的时候就加载其配置文件。<servlet>
<servlet-name>initlog4j</servlet-name>
<servlet-class>com.netstore.util.InitLog4J</servlet-class>
<init-param>
<param-name>log4j</param-name>
<param-value>WEB-INF/config.xml</param-value> 配置文件所放位置
</init-param>
<load-on-startup>2</load-on-startup> 设置启动顺序
</servlet>2。书写要加载的配置文件 config.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="FileAppender" class="org.apache.log4j.FileAppender">
<param name="File" value="d:/log.txt"/> 文件所输出的位置
<param name="Append" value="true"/> 追加输出
<layout class="org.apache.log4j.TTCCLayout"> 输出格式
<param name="dateFormat" value="yyyy-MM-dd HH:mm:ss"/>
</layout>
</appender>
<root>3。书写一个servlet,初始化log4j
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
import org.apache.log4j.xml.*;
public class InitLog4J extends HttpServlet {
private static final String CONTENT_TYPE = "text/html; charset=GBK";
public void init() throws ServletException {
String homePath = this.getServletContext().getRealPath("/");
homePath += this.getServletConfig().getInitParameter("log4j"); //得到路径
DOMConfigurator.configure(homePath); //注意
System.out.println("log4j 初始化成功!");
}//Clean up resources
public void destroy() {
}
}
<priority value ="debug" />
<appender-ref ref="FileAppender"/>
</root>
</log4j:configuration>4。使用static Logger log = Logger.getLogger(类名.class);
log4j 日志 高级使用
最新推荐文章于 2018-07-30 11:14:10 发布