java 使用log4j 日志模块

时间:2022-03-28 04:34:58

1.在工程中创建与src/main/java 同级别的config 目录

2.在config目录中创建log4j.properties 文件 并输入内容

### \u8BBE\u7F6E###
log4j.rootLogger = debug,stdout,D,E


### \u8F93\u51FA\u4FE1\u606F\u5230\u63A7\u5236\u62AC ###
log4j.appender.stdout = org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target = System.out
log4j.appender.stdout.layout = org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern = [%-5p] %d{yyyy-MM-dd HH:mm:ss,SSS} method:%l%n%m%n


### \u8F93\u51FADEBUG \u7EA7\u522B\u4EE5\u4E0A\u7684\u65E5\u5FD7\u5230=E://logs/error.log ###
log4j.appender.D = org.apache.log4j.DailyRollingFileAppender
log4j.appender.D.File = E://logs/log.log
log4j.appender.D.Append = true
log4j.appender.D.Threshold = DEBUG 
log4j.appender.D.layout = org.apache.log4j.PatternLayout
log4j.appender.D.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss}  [ %t:%r ] - [ %p ]  %m%n


### \u8F93\u51FAERROR \u7EA7\u522B\u4EE5\u4E0A\u7684\u65E5\u5FD7\u5230=E://logs/error.log ###
log4j.appender.E = org.apache.log4j.DailyRollingFileAppender
log4j.appender.E.File =E://logs/error.log 
log4j.appender.E.Append = true
log4j.appender.E.Threshold = ERROR 
log4j.appender.E.layout = org.apache.log4j.PatternLayout
log4j.appender.E.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss}  [ %t:%r ] - [ %p ]  %m%n



3.使用日志模块 封装类

  public Object methodC(){
        StackTraceElement stacks = Thread.currentThread().getStackTrace()[2];
        String AreaInfo = String.format("%s:%d:%s", stacks.getMethodName(),stacks.getLineNumber(),stacks.getFileName());
        
        return AreaInfo;
    }

4.

StackTraceElement ste = new Throwable().getStackTrace()[1];
        PropertyConfigurator.configure("config/log4j.properties");
     // 记录debug级别的信息  
        logger.debug("This is debug message."+methodC());  
        // 记录info级别的信息  
        logger.info("This is info message."+methodC());  
        // 记录error级别的信息  
        logger.error("This is error message."+methodC());