如何使用log4j的相同记录器将不同的信息写入两个不同的文件?

时间:2011-01-16 20:29:35

标签: java logging file log4j

我想使用我的记录器写入两个不同的文件,声明如下:

public static final Logger logger = Logger.getLogger(Adapt.class);
PropertyConfigurator.configure("log4j.properties");

文件log4j包含:

log4j.rootLogger=DEBUG, FA

#File Appender
log4j.appender.FA=org.apache.log4j.FileAppender
log4j.appender.FA.File=temp.ppr
log4j.appender.FA.layout=org.apache.log4j.PatternLayout
log4j.appender.FA.append=false
log4j.appender.FA.layout.ConversionPattern= %m%n

是否可以使用记录器轻松地将不同的文本写入两个不同的文件?

如果没有,有没有办法用两个记录器做到这一点? (我试过并因为函数configure而出现问题,这是静态的。)

感谢。

3 个答案:

答案 0 :(得分:6)

只需定义第二个记录器变量:

Logger otherLogger = Logger.getLogger("OTHER_LOGGER");

为其定义配置(请注意log4j。 logger .OTHER_LOGGER语法cf. log4j.rootLogger,如user623395venkatesh Dodla所指出的那样):

log4j.logger.OTHER_LOGGER=DEBUG, OtherAppender

log4j.additivity.OTHER_LOGGER = false

#File Appender
log4j.appender.OtherAppender=org.apache.log4j.FileAppender
log4j.appender.OtherAppender.File=temp2.ppr
log4j.appender.OtherAppender.layout=org.apache.log4j.PatternLayout
log4j.appender.OtherAppender.append=false
log4j.appender.OtherAppender.layout.ConversionPattern= %m%n

并照常记录您的不同文字:

logger.debug("My normal log");
otherLogger.info("My special text");

答案 1 :(得分:2)

要创建temp2.​​ppr,请从

更改
log4j.OTHER_LOGGER=DEBUG, OtherAppender

log4j.**logger**.OTHER_LOGGER=DEBUG, OtherAppender

答案 2 :(得分:2)

它对我有用。 我的日志文件:

# log4j.properties
log4j.rootLogger=DEBUG,hfis,stdout
#For second log
log4j.logger.OTHER_LOGGER=DEBUG, OtherAppender
log4j.additivity.OTHER_LOGGER = false 

#File Appender 
log4j.appender.OtherAppender=org.apache.log4j.FileAppender 
log4j.appender.OtherAppender.File=C:\\Legacy.log
log4j.appender.OtherAppender.ImmediateFlush=true 
log4j.appender.OtherAppender.layout=org.apache.log4j.PatternLayout 
log4j.appender.OtherAppender.layout.ConversionPattern=%d{dd MMM yyyy HH:mm:ss.SSS} [%t] %-5p %c - %m%n 

log4j.rootCategory=ERROR
log4j.rootLogger.additivity=false

log4j.appender.stdout.layout=org.apache.log4j.PatternLayout

log4j.appender.hfis=org.apache.log4j.RollingFileAppender
log4j.appender.hfis.Threshold=DEBUG
log4j.appender.hfis.file=C:\\hfis.log 
log4j.appender.hfis.ImmediateFlush=true
log4j.appender.hfis.MaxFileSize=5MB
log4j.appender.hfis.layout=org.apache.log4j.PatternLayout
log4j.appender.hfis.layout.ConversionPattern=%d{dd MMM yyyy HH:mm:ss.SSS} [%t] %-5p %c - %m%n
# R is the RollingFileAppender that outputs to a rolling log
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Threshold=DEBUG

# Define a pattern layout for the file.
log4j.appender.mystdout.layout=org.apache.log4j.PatternLayout
log4j.appender.mystdout.layout.ConversionPattern=%d{dd MMM yyyy HH:mm:ss.SSS} %-5p: %m%n<br>

我的日志变量是

final static Logger log = Logger.getLogger("hfis");
final static Logger log2 = Logger.getLogger("OTHER_LOGGER");