I have a Class "Example.class". I get my Logger with:
private final Logger log = Logger.getLogger(Example.class);
My log4j.properties looks like:
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=log.txt
log4j.appender.file.MaxFileSize=1024KB
log4j.appender.file.MaxBackupIndex=5
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%p %t %c - %m%n
My Class is logging via log.info(..), log.debug(..) and so on into the file . 。
Now i want to have a different logger for the same class eg:
private final Logger differentLogger = Logger.getLogger(Example.class);
and this logger should log into a different file for example
differentLogger.info("Hello World");
//writes 'Hello World' into differentLogFile.txt
Is this possible somehow?
No, the category identifies the logger.
That said, you are not forced to use the class as the category. You could use in the same class:
private final Logger log = Logger.getLogger(Example.class);
private final Logger differentLogger = Logger.getLogger(mylogs.different);
After that, in the configuration file you can define several appenders and assign each category to a different appender.
Calling Logger.getLogger(Example.class)
twice will return the same or undistinguishable instances of Logger
. This means Log4J cannot make any distinction between them and they will always land up in the same file.
The solution is obvious: use a different logger!
Logger differentLogger = Logger.getLogger("differentLogger");
And configure log4j.xml
to use different appender for differentLogger
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.