Ashu Kanaujia
Ashu Kanaujia

Reputation: 259

Log4j multiple appender independently

I am using apache log4j. I want to add 2 appenders. one for some purpose and 2nd for other. The log content are not going to both appenders. Let I have 2 appenders file1 and file2. then Logger for file1 prints the record in file1.log. andLogger for file2 prints the record in file2.log.

Upvotes: 1

Views: 4770

Answers (2)

Imran Ahmad
Imran Ahmad

Reputation: 216

Create Two appenders like below:

public static final Logger loggerOne= LoggerFactory.getLogger("com.mylogger.loggerOne");
    public static final Logger loggerTwo= LoggerFactory.getLogger("com.mylogger.loggerTwo");

Then configure your Log4j.properties file like below:

log4j.rootLogger=INFO,file ,console

log4j.logger.com.mylogger.loggerOne=INFO,firstLog
log4j.appender.firstLog.File=C:/Imran/logs/firstLog.log
log4j.appender.firstLog.DatePattern='.'yyyy-MM-dd
log4j.appender.firstLog=org.apache.log4j.DailyRollingFileAppender
log4j.appender.firstLog.layout=org.apache.log4j.PatternLayout
log4j.appender.firstLog.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L -%m%n

log4j.logger.com.mylogger.loggerTwo=INFO,secondLog
log4j.appender.secondLog.File=C:/Imran/logs/secondLog.log
log4j.appender.secondLog.DatePattern='.'yyyy-MM-dd
log4j.appender.secondLog=org.apache.log4j.DailyRollingFileAppender
log4j.appender.secondLog.layout=org.apache.log4j.PatternLayout
log4j.appender.secondLog.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L -%m%n

Use loggerOne.info() and loggerTwo.info() in you code to print in the file firstLog.log and secondLog.log respectively.

Upvotes: 1

Tan Mai Van
Tan Mai Van

Reputation: 695

You can use this snip code to log in 2 file:

log4j.rootLogger=INFO

log4j.appender.debugLog=org.apache.log4j.FileAppender
log4j.appender.debugLog.File=logs/debug.log
....

log4j.appender.reportsLog=org.apache.log4j.FileAppender
log4j.appender.reportsLog.File=logs/reports.log
....

log4j.category.debugLogger=TRACE, debugLog
log4j.additivity.debugLogger=false

log4j.category.reportsLogger=DEBUG, reportsLog
log4j.additivity.reportsLogger=false

And use this when you need to call log:

static final Logger debugLog = Logger.getLogger("debugLogger");
static final Logger resultLog = Logger.getLogger("reportsLogger");

Also if you already have log and dont want to change the log init. Log4j support you specify base on package or full quality pattern.

log4j.rootLogger=DEBUG, CONSOLE

# Each package has different appender name     
log4j.logger.com.mycorp.project.first=DEBUG, FIRST
log4j.logger.com.mycorp.project.second=DEBUG, SECOND

log4j.appender.FIRST=org.apache.log4j.RollingFileAppender
log4j.appender.FIRST.File=./first.log
log4j.appender.FIRST.layout=org.apache.log4j.PatternLayout

log4j.appender.SECOND=org.apache.log4j.RollingFileAppender
log4j.appender.SECOND.File=./second.log
log4j.appender.SECOND.layout=org.apache.log4j.PatternLayout

Upvotes: 3

Related Questions