日期:2022-05-20  浏览次数:141 次

<dependency>
  <groupId>log4j</groupId>
  <artifactId>log4j</artifactId>
  <version>1.2.17</version>
</dependency>

 

log4j.properties

### 设置###
log4j.rootLogger = debug,stdout,debugLog,infoLog,errorLog

### 输出信息到控制抬 ###
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

### 输出DEBUG 级别以上的日志 ###
log4j.appender.debugLog = org.apache.log4j.DailyRollingFileAppender
log4j.appender.debugLog.File = E://logs/debug/log.log
log4j.appender.debugLog.DatePattern = '.'yyyy-MM-dd-HH-mm'.log'
log4j.appender.debugLog.Append = true
log4j.appender.debugLog.Threshold = DEBUG
log4j.appender.debugLog.layout = org.apache.log4j.PatternLayout
log4j.appender.debugLog.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss}  [ %t:%r ] - [ %p ]  %m%n

### 输出INFO 级别以上的日志 ###
log4j.appender.infoLog = org.apache.log4j.DailyRollingFileAppender
log4j.appender.infoLog.File =E://logs/info/log.log
log4j.appender.infoLog.DatePattern = '.'yyyy-MM-dd-HH-mm'.log'
log4j.appender.infoLog.Append = true
log4j.appender.infoLog.Threshold = INFO
log4j.appender.infoLog.layout = org.apache.log4j.PatternLayout
log4j.appender.infoLog.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss}  [ %t:%r ] - [ %p ]  %m%n

### 输出ERROR 级别以上的日志 ###
log4j.appender.errorLog = org.apache.log4j.DailyRollingFileAppender
log4j.appender.errorLog.File =E://logs/error/log.log
log4j.appender.errorLog.DatePattern = '.'yyyy-MM-dd-HH-mm'.log'
log4j.appender.errorLog.Append = true
log4j.appender.errorLog.Threshold = ERROR
log4j.appender.errorLog.layout = org.apache.log4j.PatternLayout
log4j.appender.errorLog.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss}  [ %t:%r ] - [ %p ]  %m%n

 

package com.zns;

import org.apache.log4j.Logger;

public class Test1 {
    private static Logger logger = Logger.getLogger(Test1.class);
    public static void main(String[] args) {
        logger.debug("hello world");
        //logger.info("hello world");
        //logger.error("hello world");
    }
}

 

---------------下面的好用-----------------------

SLF4J+Log4J整合

增加maven配置

<dependency>
  <groupId>org.slf4j</groupId>
  <artifactId>slf4j-api</artifactId>
  <version>1.7.5</version>
</dependency>
<dependency>
  <groupId>org.slf4j</groupId>
  <artifactId>slf4j-log4j12</artifactId>
  <version>1.7.5</version>
</dependency>

 

 

最后,代码里声明logger要改一下,原来使用log4j是这样的

import org.apache.log4j.Logger;
class Test {
    final Logger logger = Logger.getLogger(Test.class);
    public void test() {
        logger.info("hello");
    }
}

 

现在要改成这样  好用

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
class Test {
    Logger logger = LoggerFactory.getLogger(Test.class);
    public void test() {
        logger.info("hello");
    }
}