[收藏此页] [打印] [推荐] [评论]Log4j中相对路径的问题

一、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文件



二、可以使用环境变量(没试过网上看的)
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中的配置<servlet>

<servlet-name>log4j-init</servlet-name>
<servlet-class>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>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值