Log4j Logging in File - BunksAllowed

BunksAllowed is an effort to facilitate Self Learning process through the provision of quality tutorials.

Random Posts



If you want to write the logging information into a file, you have to use org.apache.log4j.FileAppender. Though we have used a configuration file in our sample programs, we have not discussed the attributes. In this tutorial, we will discuss the parameters.

# First define the root logger with appender file to print the log in a file log4j.rootLogger = DEBUG, FILE # As we have mentioned that file needs to be set for logging in file log4j.appender.FILE=org.apache.log4j.FileAppender # Here, the name of the file is to be set log4j.appender.FILE.File=D:\\log.out # Perform the immediate flush after every append operation log4j.appender.FILE.ImmediateFlush=true log4j.appender.FILE.Threshold=debug # Append at the end of the log log4j.appender.FILE.Append=true log4j.appender.FILE.layout=org.apache.log4j.PatternLayout log4j.appender.FILE.layout.conversionPattern=%m%n


If you wish to create multiple files instead of writing the log in a single file as the file size grows, you may use the following configuration file. In this case, instead of using org.apache.log4j.FileAppender class, you have to use org.apache.log4j.RollingFileAppender . Moreover, you have to set the maximum file size and the maximum number of backup files.

log4j.rootLogger = DEBUG, FILE log4j.appender.FILE=org.apache.log4j.RollingFileAppender log4j.appender.FILE.File=${log}/log.out log4j.appender.FILE.ImmediateFlush=true log4j.appender.FILE.Threshold=debug log4j.appender.FILE.Append=true # Set the maximum file size which is acceptable before rollover log4j.appender.FILE.MaxFileSize=5KB # The number of backup files log4j.appender.FILE.MaxBackupIndex=2 log4j.appender.FILE.layout=org.apache.log4j.PatternLayout log4j.appender.FILE.layout.conversionPattern=%m%n


If you wish to create log files based on dates, instead of file size, you can try the following sample configuration file.
log4j.rootLogger = DEBUG, FILE log4j.appender.FILE=org.apache.log4j.DailyRollingFileAppender log4j.appender.FILE.File=${log}/log.out log4j.appender.FILE.ImmediateFlush=true log4j.appender.FILE.Threshold=debug log4j.appender.FILE.Append=true log4j.appender.FILE.DatePattern='.' yyyy-MM-dd log4j.appender.FILE.layout=org.apache.log4j.PatternLayout log4j.appender.FILE.layout.conversionPattern=%m%n


Happy Exploring!

No comments:

Post a Comment