在实际开发中,我们需要将项目分层(DAO层、Service层、Action控制层),我了我们方便分析日志。我们需要将日志按照java包输出到不同的日志文件中去,甚至是不同的文件夹下面去,这时候我们就需要用Log4j按包名输出日志。下面通过一个实例来讲解Log4j该怎样来配置。
项目的整体结构如下图:
log4j配置文件如下:
log4j.rootLogger=info,console # 这里指定不同的包输出到那个appender上面 log4j.logger.com.huangx=info,huangx log4j.logger.com.bug315=info,bug315 # console appender log4j.appender.console=org.apache.log4j.ConsoleAppender log4j.appender.console.layout=org.apache.log4j.PatternLayout log4j.appender.console.layout.ConversionPattern=%d %p [%c] - %m%n # file appender log4j.appender.file=org.apache.log4j.RollingFileAppender log4j.appender.file.File=F:/Eclipse_Logging/Logging_Log4j_Learn/document/log.txt log4j.appender.file.layout=org.apache.log4j.PatternLayout log4j.appender.file.layout.ConversionPattern=%d %p [%c] - %m%n # com.huangx.* log4j.appender.huangx=org.apache.log4j.RollingFileAppender log4j.appender.huangx.File=F:/Eclipse_Logging/Logging_Log4j_Learn/document/huangx.log log4j.appender.huangx.layout=org.apache.log4j.PatternLayout log4j.appender.huangx.layout.ConversionPattern=%d %p [%c] - %m%n # com.bug315.* log4j.appender.bug315=org.apache.log4j.RollingFileAppender log4j.appender.bug315.File=F:/Eclipse_Logging/Logging_Log4j_Learn/document/bug315.log log4j.appender.bug315.layout=org.apache.log4j.PatternLayout log4j.appender.bug315.layout.ConversionPattern=%d %p [%c] - %m%n
java代码文件如下:
package com.bug315; import org.apache.log4j.Logger; import com.huangx.Test2; public class Test { public static void main(String[] args) { Logger log = Logger.getLogger( Test.class ); log.debug("debug infomation"); log.info("info infomation"); log.warn("warn infomation"); log.error("error infomation"); Test2 t2 = new Test2(); t2.show(); } } package com.huangx; import org.apache.log4j.Logger; public class Test2 { public void show() { Logger log = Logger.getLogger( Test2.class ); log.debug("debug infomation"); log.info("info infomation"); log.warn("warn infomation"); log.error("error infomation"); } }
输出结果如下图:
到这里就实现了log4j按包输出日志,推荐阅读Log4j日志级别