日期:2014-05-19  浏览次数:20789 次

请问如何将log4j各个级别的日志分别输出到不同的文件中?
如题,
比如我要将   info级别的信息写到info.txt
                      error级别的信息写到error.txt   ?

------解决方案--------------------
都设置多个好了

log4j.logger.forDebug=DEBUG,debugAppender
log4j.appender.debugAppender=org.apache.log4j.DailyRollingFileAppender

log4j.logger.forInfo=INFO,infoAppender
log4j.appender.infoAppender=org.apache.log4j.DailyRollingFileAppender

..........................


调用的时候
static Logger debugLogger = Logger.getLogger( "forDebug ");
static Logger infoLogger = Logger.getLogger( "forInfo ");
..........................


------解决方案--------------------
log4j支持这个功能,不过不能再使用Properties配置,必须使用XML

建一个log4j.xml
<?xml version= "1.0 " encoding= "UTF-8 "?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd ">
<log4j:configuration xmlns:log4j= "http://jakarta.apache.org/log4j/ ">
<appender name= "STDOUT " class= "org.apache.log4j.ConsoleAppender ">
<layout class= "org.apache.log4j.PatternLayout "/>
</appender>
<appender name= "DEBUG " class= "org.apache.log4j.RollingFileAppender ">
<param name= "File " value= "debug.log "/>
<param name= "Append " value= "true "/>
<param name= "MaxFileSize " value= "500KB "/>
<param name= "MaxBackupIndex " value= "2 "/>
<layout class= "org.apache.log4j.PatternLayout "/>
<filter class= "org.apache.log4j.varia.LevelRangeFilter ">
<param name= "LevelMax " value= "DEBUG " />
<param name= "LevelMin " value= "DEBUG " />
</filter>
</appender>
<appender name= "INFO " class= "org.apache.log4j.RollingFileAppender ">
<param name= "File " value= "info.log "/>
<param name= "Append " value= "true "/>
<param name= "MaxFileSize " value= "500KB "/>
<param name= "MaxBackupIndex " value= "2 "/>
<layout class= "org.apache.log4j.PatternLayout "/>
<filter class= "org.apache.log4j.varia.LevelRangeFilter ">
<param name= "LevelMax " value= "INFO " />
<param name= "LevelMin " value= "INFO " />
</filter>
</appender>
<root>
<appender-ref ref= "STDOUT "/>
<appender-ref ref= "DEBUG "/>
<appender-ref ref= "INFO "/>
</root>
</log4j:configuration>

代码中DOMConfigurator.configure( "log4j.xml ");


这样就可以在log.debug和log.info时分别打印到不同文件中,如果你还需要更多的文件,可以复制多几次appender就可以了