尝试将log4j的文件日志输出到web工程制定目录,遇到了很多问题,最终搞定,下面是记录。
其原理在于log4j的配置文件支持服务器的vm的环境变量,如${oss.log4j.path},在log4j加载配置文件之前,先用System.setProperty("", "")设置好日志文件路径,这一操作通过一个初始的servlet来实现
1. log4j.properties文件
class="java">
log4j.rootCategory=debug,stdout,ROLLFILE,R
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] (%F:%L) -%m%n
log4j.appender.R=org.apache.log4j.RollingFileAppender
log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern=%p %t %c -%m%n
log4j.appender.R.File=${oss.log4j.path}logs/log.log
log4j.appender.R.MaxFileSize=100KB
log4j.appender.R.MaxBackupIndex=1
log4j.appender.ROLLFILE = org.apache.log4j.DailyRollingFileAppender
log4j.appender.ROLLFILE.File = ${oss.log4j.path}logs/log.html
log4j.appender.ROLLFILE.Append = true
log4j.appender.ROLLFILE.Threshold = DEBUG
log4j.appender.ROLLFILE.layout = org.apache.log4j.HTMLLayout
2. servlet。配置web服务器的vm环境变量
package com.jesse.onlineshop.servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import org.apache.log4j.Logger;
/**
* 将配置信息读入系统变量
* @author Administrator
*
*/
public class SystemServlet extends HttpServlet {
private static final Logger logger = Logger.getLogger(SystemServlet.class);
private static final long serialVersionUID = -833322220864312415L;
@Override
public void init() throws ServletException {
String rootPath = this.getServletContext().getRealPath("/");
logger.info(rootPath);
String log4jPath = this.getServletConfig().getInitParameter("oss.log4j.path");
//若没有指定oss.log4j.path初始参数,则使用WEB的工程目录
log4jPath = (log4jPath==null||"".equals(log4jPath))?rootPath:log4jPath;
System.setProperty("oss.log4j.path", log4jPath);
super.init();
}
}
3. web.xml. 不需要配置servlet-mapping,load-on-startup设置为0,会在web容器启动时候就装入该servlet
<servlet>
<servlet-name>systemServlet</servlet-name>
<servlet-class>com.jesse.onlineshop.servlet.SystemServlet</servlet-class>
<init-param>
<param-name>oss.log4j.path</param-name>
<param-value></param-value>
</init-param>
<load-on-startup>0</load-on-startup>
</servlet>
4. 结果
5. 疑惑
在log4j.properties配置文件中,日志文件路径需要配置成${oss.log4j.path}logs/log.html
在配制成${oss.log4j.path}/logs/log.html时不能输出,但是通过输出System.getProperty("oss.log4j.path")时输出的路径并不包含"/"。所以不
理解为什么最终会在这里加上一个"/"的。