log4j log file names?

2020-02-04 02:27发布

We have several jobs that run concurrently that have to use the same config info for log4j. They are all dumping the logs into one file using the same appender. Is there a way to have each job dynamically name its log file so they stay seperate?

Thanks
Tom

10条回答
2楼-- · 2020-02-04 03:17

Tom you coud specify and appenders for each job. Let's that you have 2 jobs corresponding to two different java packages com.tom.firstbatch and com.tom.secondbatch, you would have something like this in log4j.xml :

   <category name="com.tom.firstbatch">
      <appender-ref ref="FIRST_APPENDER"/>
   </category>
   <category name="com.tom.secondtbatch">
      <appender-ref ref="SECOND_APPENDER"/>
   </category>
查看更多
Explosion°爆炸
3楼-- · 2020-02-04 03:26

Building on shadit's answer. If each job can be identified by which class' main method was started you can use the system property sun.java.command that contais the full name of the class started. For instance like this:

log4j.appender.LOGFILE.File=${sun.java.command}.log

I use it together with a TimestampFileAppender like this:

log4j.appender.LOGFILE=TimestampFileAppender
log4j.appender.LOGFILE.TimestampPattern=yyyy_MM_dd__HH_mm
log4j.appender.LOGFILE.File=${sun.java.command}_{timestamp}.log

This way when I'm developing in Eclipse I get a new log file for each new process that I run, identified by the classname of the class with the main method and the time it was started.

查看更多
我欲成王,谁敢阻挡
4楼-- · 2020-02-04 03:27

Can you pass a Java system property for each job? If so, you can parameterize like this:

java -Dmy_var=somevalue my.job.Classname

And then in your log4j.properties:

log4j.appender.A.File=${my_var}/A.log

You could populate the Java system property with a value from the host's environment (for example) that would uniquely identify the instance of the job.

查看更多
爷的心禁止访问
5楼-- · 2020-02-04 03:28

You could write your own appender that makes up its own filename, perhaps using the [File.createTempFile](http://java.sun.com/j2se/1.5.0/docs/api/java/io/File.html#createTempFile(java.lang.String,%20java.lang.String)) method. If the FileAppender class was written correctly, you should be able to extend it—or RollingFileAppender—and override the getFile method to return one that you choose based on whatever new properties you would like to add.

查看更多
登录 后发表回答