In Java, normally we use log4j or java.util.Logger to create log files. Log4j uses the attributes mentioned in log4j.properties file for this. By default, log4j will look in to the WebContent/WEB-INF/classes directory for the properties file. A sample log4j property file is given below.
log.dir=/mylogs
rrd.dir=${log.dir}/rrd
datestamp=yyyy-MM-dd HH:mm:ss.SSS
roll.pattern.hourly=.yyyy-MM-dd.HH
roll.pattern.daily=.yyyy-MM-dd
log4j.rootLogger=DEBUG,testlogger
log4j.appender.testlogger=org.apache.log4j.DailyRollingFileAppender
log4j.appender.testlogger.File=${log.dir}/test.log
log4j.appender.testlogger.DatePattern=${roll.pattern.daily}
log4j.appender.testlogger.layout=org.apache.log4j.PatternLayout
Here, the logs will be generated in a log file named test.log inside the directory mylogs.
Using log4j, it is possible to write logs to different files based on the package name. For that, we need to mention different log handler based on the package name. For eg: suppose you want to print all the logs generated by the java classes present under the package com.test. For this, you need to define a handler as follows.
log4j.logger.com.test=DEBUG, testpackageLogger
Now you can mention the file where the logs from com.test package needs to be printed as below.
log4j.appender.testpackageLogger.File=${log.dir}/testpackage.log
Similarly, for different package named com.temp, you can define a new handler similar to above in the same log4j.properties file
log4j.logger.com.temp=DEBUG, temppackageLogger
log4j.appender.temppackageLogger.File=${log.dir}/temppackage.log
The logs generated by the classes which are not present in these packages will get printed in the log file mentioned under rootLogger configuration mentioned above.
Please note that the logs generated by the classes present under com.test and com.temp will also get generated inside the log file mentioned in rootLogger. To avoid that, you can use log4j additivity property
log4j.additivity.com.test=false
By setting its value as false, the logs will get printed only inside the package specific log file.
No comments:
Post a Comment