java log4j 动态配置文件,如何在log4j.xml的附加程序中提供动态文件名

I am using log4j to log information. I have used a log4j.xml file for creating log files. I have given the absolute path for each log file as a param tag value.

E.g.:

I do not want to write "GPreprocessor.log" directly. Actually, that file name is dynamic, based on my project's name. For example, if I run the program ABC.java, logging should go to D:/logFiles/ABC.log, but if I run XYZ.java, logging should go to D:/logFiles/XYZ.log. The file's location will always remain the same: D:/logFiles/. How can I change the log file's name dynamically?

解决方案

It's much easier to do the following:

In log4j.xml define variable as ${variable}:

Then make sure you set the system property when you start your JVM such as:

java -Dlogfilename=my_fancy_filename example.Application

That will create a dynamic log file name: my_fancy_filename.log

Alternatively, you can set the system property in code so long as you do it before you create a logger (this is useful if you want your PID in your logs for instance). Such as:

System.setProperty("logfilename", "a_cool_logname");

Once that is set you can go ahead and get your loggers as normal and they will log to the dynamic file (be careful of those static Loggers that create loggers before your main method executes).

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值