Lalchand
Lalchand

Reputation: 7827

multiple fileappenders in log4j

I have to put the log info in two separate log files based on some condition.how to do that. here is my logging.properties file

log4j.rootLogger=debug, stdout, R
log4j.appender.stdout=org.apache.log4j.RollingFileAppender
log4j.appender.stdout.File=${catalina.home}/logs/std.log
log4j.appender.stdout.MaxFileSize=200KB
log4j.appender.stdout.MaxBackupIndex=2
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d [%c] %p - %m%n


log4j.appender.R=org.apache.log4j.RollingFileAppender
log4j.appender.R.File=${catalina.home}/logs/demo.log
log4j.appender.R.MaxFileSize=200KB
log4j.appender.R.MaxBackupIndex=2
log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern=%d [%c] %p - %m%n

Upvotes: 3

Views: 14589

Answers (3)

Qwerky
Qwerky

Reputation: 18435

You can define multiple appenders and assign java packages to the appenders. In the example below all classes in com.mycorp.web will log to web.log at DEBUG level and classes in com.mycorp.db will log to db.log at INFO level.

log4j.rootLogger=debug, weblogger, dblogger

#Define which packages use which appenders
log4j.logger.com.mycorp.web=DEBUG,weblogger
log4j.logger.com.mycorp.db=INFO,dblogger

#Ensure the logs don't add to each other
log4j.additivity.com.mycorp.web=false
log4j.additivity.com.mycorp.db=false

#Define web appender
log4j.appender.weblogger=org.apache.log4j.DailyRollingFileAppender
log4j.appender.weblogger.File=/var/log/myapp/web.log
log4j.appender.weblogger.DatePattern='.'yyyy-MM-dd
log4j.appender.weblogger.Append=true
log4j.appender.weblogger.layout=org.apache.log4j.PatternLayout
log4j.appender.weblogger.layout.ConversionPattern=%d [%t] %-5p %c{1} - %m %n

#Define db appender
log4j.appender.dblogger=org.apache.log4j.DailyRollingFileAppender
log4j.appender.dblogger.File=/var/log/myapp/db.log
log4j.appender.dblogger.DatePattern='.'yyyy-MM-dd
log4j.appender.dblogger.Append=true
log4j.appender.dblogger.layout=org.apache.log4j.PatternLayout
log4j.appender.dblogger.layout.ConversionPattern=%d [%t] %-5p %c{1} - %m %n

Upvotes: 11

MarrLiss
MarrLiss

Reputation: 808

If you want different file for some logger, you should write something like this:

log4j.logger.LOGGER_ONE=DEBUG, stdout
log4j.logger.LOGGER_TWO=WARN, R

Upvotes: 0

Jeremy
Jeremy

Reputation: 22415

Based on your condition, you can grab different loggers.

Logger x = predicate() ? Logger.getLogger("wombat") : Logger.getLogger("other");

http://logging.apache.org/log4j/1.2/manual.html (Search for "wombat" for the relevant code.)

Upvotes: 0

Related Questions