log4j配置相对路径实现日志记录
从网上简单搜索了一下,发现有三种介绍的方法。总结在这里 [b]1. 解决的办法自然是想办法用相对路径代替绝对路径[/b] 其实log4j的FileAppender本身就有这样的机制,如:log4j.appender.logfile.File=${WORKDIR}/logs/app.log其中“${WORKDIR}/”是个变量,会被System Property中的“WORKDIR”的值代替。这样,我们就可以在log4j加载配置文件之前,先用System.setProperty设置好根路径。 [b]2.可以使用环境变量[/b] log4j.appender.R=org.apache.log4j.RollingFileAppender log4j.appender.R.File=${catalina.base}/logs/logs_tomcat.log log4j.appender.R.MaxFileSize=10KB [b]3.具体实现[/b] (1)一般在我们开发项目过程中,log4j日志输出路径固定到某个文件夹,这样如果我换一个环境,日志路径又需要重新修改,比较不方便,目前我采用了动态改变日志路径方法来实现相对路径保存日志文件 [code]public class Log4jInit extends HttpServlet { static Logger logger = Logger.getLogger(Log4jInit.class); public Log4jInit() { } public void init(ServletConfig config) throws ServletException { String prefix = config.getServletContext().getRealPath("/"); String file = config.getInitParameter("log4j"); String filePath = prefix + file; Properties props = new Properties(); try { FileInputStream istream = new FileInputStream(filePath); props.load(istream); istream.close(); //toPrint(props.getProperty("log4j.appender.file.File")); String logFile = prefix + props.getProperty("log4j.appender.file.File");//设置路径 props.setProperty("log4j.appender.file.File",logFile); PropertyConfigurator.configure(props);//装入log4j配置信息 } catch (IOException e) { toPrint("Could not read configuration file [" + filePath + "]."); toPrint("Ignoring configuration file [" + filePath + "]."); return; } } public static void toPrint(String content) { System.out.println(content); } } [/code] (2).Web.xml中的配置 [code] log4j-init Log4jInit log4j WEB-INF/classes/log4j.properties 1 [/code]