How to create process based log file using Log4j?

狂风中的少年 提交于 2019-12-06 15:15:31

One solution could be use System Variables. You can write something like this in your log4j.xml

<appender name="ProductionLog" class="org.apache.log4j.RollingFileAppender">
    <param name="File" value="c:/logs/myLog-${myProcId}.log"/>
    <param name="Append" value="true"/>
    <param name="MaxFileSize" value="10000KB"/>
    <param name="MaxBackupIndex" value="10"/>
    <layout class="org.apache.log4j.EnhancedPatternLayout">
        <param name="ConversionPattern" value="[%d] [%-5p] {%c|%t}: %m%n"/>
    </layout>
</appender>

Important is that usage of system variable ${myProcId}
You can provide system variable for example before you initialize Log4j e.g.

System.setProperty("myProcId", procId);
DOMConfigurator.configure(log4jFilePath);

There are many ways to do it, personally I would instrument the logs with extra information and then use log processing to split them back out again. If you are Linux based then this should be pretty easy and transfers the extra processing to read time rather than write time.

Ways to add extra information would be: -

  • Named thread pools for each process then include that in your pattern
  • NDC to add context specific information (this is what I use)

Another approach would be to use separate loggers which are intitialised by the constructor with a specific name (ProcessA, ProcessB). When you instantiate your dependencies you can then pass in the alternate logger name to use in the constructor or via property injection. If you are using Spring this will be easy, if not then I expect the factory pattern is your friend here.

Hope this helps.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!