首先需要配置web.xml里面:
<servlet-name>log4j-init</servlet-name> <servlet-class>com.free.core.util.Log4j</servlet-class> <init-param> <param-name>log4j</param-name> <param-value>/WEB-INF/classes/logxml/log4j.xml</param-value> </init-param> <load-on-startup>1</load-on-startup>
之后需要写一个实现类
package com.free.core.util; import java.io.File; import javax.servlet.http.HttpServlet; import org.apache.log4j.xml.DOMConfigurator; public class Log4j extends HttpServlet { private static final long serialVersionUID = -4046002537330149394L; public void init() { String path = this.getServletContext().getRealPath("/"); String file = this.getInitParameter("log4j"); String log4jPath = path + file; System.setProperty("home", path); DOMConfigurator.configure(log4jPath); } }
logxml/log4j.xml配置deom:
<!-- 输出到日志文件 按照文件大小 --> <appender name="log_roll" class="org.apache.log4j.DailyRollingFileAppender"> <!-- 设置File参数:日志输出文件名 --> <param name="File" value="${home}/logs/SystemOut.log" /> <!-- 在DailyRollingFileAppender中可以指定monthly(每月)、 weekly(每周)、daily(每天)、half-daily(每半天)、hourly(每小时)和minutely(每分钟)六个频度,这是通过为DatePattern选项赋予不同的值来完成的。DatePattern选项的有效值为: --> <param name="datePattern" value="‘.‘yyyy-MM-dd" /> <!-- 是否使用BufferedWriter进行包装,写入数据量到达bufferSize之后写入 --> <param name="bufferedIO" value="false" /> <!-- 设置缓存大小 --> <param name="bufferSize" value="65536" /> <!-- 设置是否在重新启动服务时,在原有日志的基础添加新日志 --> <param name="Append" value="false" /> <!-- 设置文件大小 --> <param name="MaxFileSize" value="2000KB" /> <!-- 设置文件备份 --> <param name="MaxBackupIndex" value="10" /> <!-- 设置输出文件项目和格式 --> <layout class="org.apache.log4j.PatternLayout"> <param name="ConversionPattern" value="[%p] [%d{yyyy-MM-dd HH:mm:ss}] [ Class = %C | Method = %M | Line = %L ] | MSG = %m |%n" /> </layout> <filter class="org.apache.log4j.varia.LevelRangeFilter"> <param name="LevelMax" value="WARN" /> <param name="LevelMin" value="TRACE" /> </filter> </appender>
原文地址:https://www.cnblogs.com/diandianquanquan/p/11496480.html
时间: 2024-10-06 00:30:53