Java – Creating Different log files using log4j

javalog4j

I am trying to write logs in different files. I want to be able to write into different files from different methods. Say if there is an exception in Method A it writes in File A…if there is an exception in Method B write in File B. I read help on google, but they all suggest the debug, trace etc etc levels. My messages are all error messages, just the methods are different. I am using properties file for log4j. This is what it looks like:

log4j.rootLogger=ERROR, ROOT
log4j.appender.ROOT=org.apache.log4j.RollingFileAppender
log4j.appender.ROOT.File=(**my_path**)\EmailIntegration.log
log4j.appender.ROOT.MaxFileSize=1000KB
log4j.appender.ROOT.MaxBackupIndex=5
log4j.appender.ROOT.layout=org.apache.log4j.PatternLayout 
log4j.appender.ROOT.layout.ConversionPattern=[%d] %t %c %-5p - %m%n
log4j.logger.com.webage.ejbs=INFO

Best Answer

  1. Define your log4j.rootLogger.
  2. Configure your rootLogger to an appender.
  3. Define what root logger must the class log to.

Example (my root logger is stdout, infoout, debugout, errorout).

#---This is the configuration file for Log4J---
log4j.threshold=ALL
log4j.rootLogger=ALL, stdout, infoout, debugout, errorout

Then I defined each logger (e.g. infoout)

#--Log settings for infoout
log4j.appender.infoout=org.apache.log4j.RollingFileAppender
log4j.appender.infoout.file=C:/Logs/Music4Point0.info.log
log4j.appender.infoout.MaxFileSize=10240KB
log4j.appender.infoout.MaxBackupIndex=10
log4j.appender.infoout.layout=org.apache.log4j.PatternLayout
log4j.appender.infoout.layout.ConversionPattern=%d{dd-MMM-yyy HH:mm:ss,SSS} [%t] %-5p %c - %m%n
log4j.appender.infoout.Threshold=INFO

Now, I said that all org.hibernate.* classes must log to DEBUG threshold and infoout logger.

log4j.logger.org.hibernate=DEBUG, infoout
log4j.additivity.org.hibernate=false

That's how you configure log4J to setup your custom logging.

Related Topic