Multiple files with Log4j

2019-08-02 10:56发布

问题:

I'm using log4j to log several informations. I'd like to separate these infos into multiple files.

My configuration file is similar to this:

      #logger_1
            log4j.logger.logger_1=debug, logger_1_File
            log4j.appender.logger_1_File=org.apache.log4j.RollingFileAppender
            log4j.appender.logger_1_File.layout=org.apache.log4j.PatternLayout
            log4j.appender.logger_1_File.layout.ConversionPattern=%d{ABSOLUTE} %m%n
            log4j.appender.logger_1_File.File=${webinf}/logs/logger1/logger1.log
            log4j.appender.logger_1_File.MaxFileSize=5000KB
            log4j.appender.logger_1_File.MaxBackupIndex=200
            log4j.appender.logger_1_File.encoding=UTF-8

        #logger_2
            log4j.logger.logger_2=debug, logger_2_File
            log4j.appender.logger_2_File=org.apache.log4j.RollingFileAppender
            log4j.appender.logger_2_File.layout=org.apache.log4j.PatternLayout
            log4j.appender.logger_2_File.layout.ConversionPattern=%d{ABSOLUTE} %m%n
            log4j.appender.logger_2_File.File=${webinf}/logs/logger2/logger2.log
            log4j.appender.logger_2_File.MaxFileSize=5000KB
            log4j.appender.logger_2_File.MaxBackupIndex=200
            log4j.appender.logger_2_File.encoding=UTF-8

...

I have two questions about it:

  1. Is there any way I could abbreviate this (omit the repeated/boilerplate code)? I have to repeat a lot of line when I use several appenders.
  2. Is there any performance problem with it? This config means log4j holds several resources to write into files. Does it cause performance problems? I have 9 appenders like these so I'm worried about it.

回答1:

First of all, measure the performance of your app with a single appender, with many appenders, with different log levels. If you have a performance issue, you need to solve it, otherwise no need to worry about it.

Also read the "Performance" section at the end of the Short introduction to log4j.