Samurai
Samurai

Reputation: 843

How to create process based log file using Log4j?

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?

Upvotes: 1

Views: 1418

Answers (2)

James
James

Reputation: 1571

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.

Upvotes: 0

bugs_
bugs_

Reputation: 3714

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

Upvotes: 1

Related Questions