Log4j中相对路径的问题怎么解决
导读:本文共1568字符,通常情况下阅读需要5分钟。同时您也可以点击右侧朗读,来听本文内容。按键盘←(左) →(右) 方向键可以翻页。
摘要: 一、properties文件中:log4j.appender.logfile.File=${WORKDIR}/logs/app.log其中“${WORKDIR}/”是个变量,会被System Property中的“WORKDIR”的值代替。这样,我们就可以在log4j加载配置文件之前,先用System.setProperty设置好根路径。jsp中可以这样:Str... ...
目录
(为您整理了一些要点),点击可以直达。一、properties文件中:
log4j.appender.logfile.File=${WORKDIR}/logs/app.log
其中“${WORKDIR}/”是个变量,会被System Property中的“WORKDIR”的值代替。这样,我们就可以在log4j加载配置文件之前,先用System.setProperty设置好根路径。
jsp中可以这样:
String path = pageContext.getServletContext().getRealPath("/");
String realPath = path+"WEB-INFclasseslog4j.properties";
System.setProperty("WORKDIR",path.replace("","/"));
PropertyConfigurator.configure(realPath.replace("","//"));//加载.properties文件
[@more@]
二、可以使用环境变量(没试过网上看的)
log4j.appender.R=org.apache.log4j.RollingFileAppender
log4j.appender.R.File=${catalina.base}/logs/logs_tomcat.log
log4j.appender.R.MaxFileSize=10KB
三、具体实现:(没试过网上看的)
一般在我们开发项目过程中,log4j日志输出路径固定到某个文件夹,这样如果我换一个环境,日志路径又需要重新修改,比较不方便,目前我采用了动态改变日志路径方法来实现相对路径保存日志文件
(1).在项目启动时,装入初始化类:
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);
}
}
(2).Web.xml中的配置
Log4j中相对路径的问题怎么解决的详细内容,希望对您有所帮助,信息来源于网络。