0

I would like to ask about log4j

How to generate multiple log4j file for each class executed?

So I have 4 classes on my project and right now I set my log4j using log4j.properties utilizing FileAppender so that it only generates one log for all classes.

I would like to have log files per class. If I had 4 classes (A,B,C,D), I'd like to have A.log, B.log, C.log, and D.log containing information regarding log activity of each class.

Thank you very much.

Raymond
  • 604
  • 1
  • 9
  • 27
  • Hope following link will give you some idea. http://stackoverflow.com/questions/10630522/how-to-create-different-log-files-for-different-packages-using-same-log4j-logger – Sivakumar Jul 16 '14 at 08:47

2 Answers2

1

You can have your log4j configuration having multiple appender's pointing to different packages

<!-- pkg1 --> 
<appender name="LogFromPackage1" class="org.apache.log4j.FileAppender">
    <param name="File" value="pkg1.log" />
    <param name="Threshold" value="ERROR" />
    <layout class="org.apache.log4j.PatternLayout">
        <param name="ConversionPattern" value="%-5p %t [%-40.40c] %x - %m%n"/>
    </layout>
</appender> 

<logger name="com.mypkg.pkg1">
    <appender-ref ref="LogFromPackage1"/>
</logger>

<!-- pkg2 -->
<appender name="LOGFromPackage2" class="org.apache.log4j.FileAppender">
    <param name="File" value="pkg2.log" />
    <layout class="org.apache.log4j.PatternLayout">
        <param name="ConversionPattern" value="%-5p %t [%-40.40c] %x - %m%n"/>
    </layout>
</appender>

<logger name="com.mypkg.pkg2">
    <appender-ref ref="LOGFromPackage2"/>
</logger>
vinayknl
  • 1,242
  • 8
  • 18
0

I had found a way to do it! Modify log4jproperties dynamically!

private void updateLog4jConfig(String className){

    Properties props = new Properties();
    try{
        InputStream configStream = getClass().getResourceAsStream("/log4j.properties");
        props.load(configStream);
        configStream.close();
    } catch(IOException ie){
        System.out.println("ERROR! Cannot load Configuration File....");
    }
    props.setProperty("log4j.appender.LOGGER.File", "./logs/"+className+".log");
    org.apache.log4j.LogManager.resetConfiguration();
    PropertyConfigurator.configure(props);

}

Cheers!

Raymond
  • 604
  • 1
  • 9
  • 27
  • 1
    I bet it is not going to work if you have all those classes in same process. The last one which run this piece of code will decide the log file name. – Adrian Shum Jul 17 '14 at 03:59
  • It works for mine, as I run classes individually in a suite. No, it will generate log file per class. When class A finished being executed, the log file for A is stopped. Class B is executed later on, and the log file prints log file for class B within the log file name for class B. So on and so forth. – Raymond Jul 18 '14 at 03:18