Sample codes to configure log4j
General logger initialization
Logger logger = Logger.getLogger(YourClass.class);log4j.properties file sample (writes to file too)
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
#log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
#log4j.appender.stdout.layout.ConversionPattern=%d{DATE} %5p [%c]:%L - %m%n
#log4j.appender.stdout.layout.ConversionPattern=%d{ISO8601} %5p [%c]:%L - %m%n
#Same as ISO8601
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd'T'HH:mm:ss.S Z} %5p [%c]:%L - %m%n
#log4j.appender.stdout.layout.ConversionPattern=%d{ISO8601} %5p [%c]:%L - %m%n
#Same as ISO8601
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd'T'HH:mm:ss.S Z} %5p [%c]:%L - %m%n
log4j.appender.stdout.Threshold=trace
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=${user.dir}/you_log_file.log
log4j.appender.file.MaxFileSize=10MB
log4j.appender.file.MaxBackupIndex=10
log4j.appender.file.layout=org.apache.log4j.PatternLayout
### set log levels - for more verbose logging change 'info' to 'debug' ###
log4j.rootLogger=trace, stdout, file
Additional file outputs [2 sample layouts]
//Load the file handler for the logger 1
Appender fh = new FileAppender(new SimpleLayout(), workingDir + File.separator + logfile);
logger.addAppender(fh);
fh.setLayout(new SimpleLayout());
//Load the file handler for the logger 2
TTCCLayout logLayout = new TTCCLayout();
logLayout.setDateFormat("dd MMM yyyy HH:mm:ss,SSS");
Appender fh = new FileAppender(logLayout, workingDir + File.separator + logfile);
logger.addAppender(fh);
fh.setLayout(logLayout);
More options available with 'Enhanced Pattern Layout' and 'Layout'
Ref:
http://www.mkyong.com/logging/log4j-log4j-properties-examples/
http://stackoverflow.com/questions/4474646/how-to-write-to-a-text-file-using-to-log4j
API:
https://logging.apache.org/log4j/1.2/apidocs/index.html
No comments:
Post a Comment