通过Servlet初始化参数配置Log4j, 并将日志保存在磁盘上.
新建Servlet并配置启动参数
新建一个Servlet: log4jInit.java, 建立完之后,前往web.xml文件找到配置项, 添加初始化名和参数值.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| <servlet> <display-name>Log4jInit</display-name> <servlet-name>Log4jInit</servlet-name> <servlet-class>com.xxxx.util.Log4jInit</servlet-class> <init-param> <param-name>log4j</param-name> <param-value>WEB-INF/classes/log4j.properties</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet>
|
Servlet的init()方法中配置log4j
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
| package com.xxxx.util;
import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet;
import org.apache.log4j.PropertyConfigurator;
public class Log4jInit extends HttpServlet { public void init(ServletConfig config) throws ServletException {
String projectRealPath = getServletContext().getRealPath("/");
System.setProperty("projectRealPath", projectRealPath);
String log4jPropertiesFilePath = config.getInitParameter("log4j");
if (log4jPropertiesFilePath != null) { PropertyConfigurator.configure(projectRealPath + log4jPropertiesFilePath); } } }
|
log4j.properties中引用项目路径
${projectRealPath}/log/logFile.log
代表我们将log文件生成在项目所在的目录里面,这也是我们在Servlet中通过System.setProperty("projectRealPath", projectRealPath);
设置的一个系统属性.
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| log4j.rootLogger=debug,stdout,D
log4j.appender.stdout = org.apache.log4j.ConsoleAppender log4j.appender.stdout.Target = System.out log4j.appender.stdout.layout = org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern = [%-5p] [%d{yyyy-MM-dd HH\:mm\:ss}] [method\:%l]%n%m%n
### 用于将日志保存在磁盘上. log4j.appender.D = org.apache.log4j.DailyRollingFileAppender # 日志的记录周期为每天保存一次。 log4j.appender.D.File =${projectRealPath}/log/logFile.log # 日志保存的路径。 log4j.appender.D.Append = true log4j.appender.D.Threshold = DEBUG log4j.appender.D.layout = org.apache.log4j.PatternLayout log4j.appender.D.layout.ConversionPattern=[%-5p] [%d{yyyy-MM-dd HH\:mm\:ss}] [method\:%l]%n%m%n
|