Reputation: 614
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.
Upvotes: 0
Views: 1067
Reputation: 614
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!
Upvotes: 0
Reputation: 1252
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>
Upvotes: 1