How to create process based log file using Log4j?

不问归期 提交于 2019-12-08 03:56:28

问题


below are my class details. ClassA and ClassD are runnable classes. From ClassA I am calling ClassB and ClassC.

package comp1 -> Contains ClassA, ClassB, ClassC
package comp2 -> Contains ClassD, ClassE

Log for comp1 -> comp1.log
Log for comp2 -> comp2.log

I am using Log4j for logging. I have two loggers based on package name. I am calling ClassE and ClassB from ClassD. Now, comp1.log contains logging messages from ClassB and comp2.log contains log froms ClassD and ClassE.

How can I make a process based log? If I run ClassD there should only one log file for ClassD, ClassE and ClassB. Is this possible using Log4j?


回答1:


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);



回答2:


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.



来源:https://stackoverflow.com/questions/11984414/how-to-create-process-based-log-file-using-log4j

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