• 【JAVA】日志管理slf4j


    前言

    这边文章描述怎么使用slf4j.

    1.使用步骤

    a.maven导入依赖

        <!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-api -->
        <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>
          <!-- <scope>test</scope> -->
        </dependency>

    b.在resources路径下添加配置文件  log4j.properties

    ### 设置###
    log4j.rootLogger=debug,stdout,D,E
    ### 输出信息到控制抬 ###
    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 级别以上的日志到=E://logs/error.log ###
    log4j.appender.D=org.apache.log4j.DailyRollingFileAppender
    log4j.appender.D.File=D://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
    ### 输出ERROR 级别以上的日志到=E://logs/error.log ###
    log4j.appender.E=org.apache.log4j.DailyRollingFileAppender
    log4j.appender.E.File=D://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

    c.添加java代码

    public class Log4jTestDemo {
    
      private static Logger logger = LoggerFactory.getLogger(Log4jTestDemo.class);
    
      public static void main(String[] args) {
        System.out.println("This is println message.");
    
        // 记录debug级别的信息
        logger.debug("This is debug message.");
        // 记录info级别的信息
        logger.info("This is info message.");
        // 记录error级别的信息
        logger.error("This is error message.");
      }
    }

    2.常见的问题

    a.提示下面错误

    SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
    SLF4J: Defaulting to no-operation (NOP) logger implementation
    SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.

    原因是因为导入maven时没有导入

        <dependency>
          <groupId>org.slf4j</groupId>
          <artifactId>slf4j-log4j12</artifactId>
          <version>1.7.5</version>
          <!-- <scope>test</scope> -->
        </dependency>
    Ride the wave as long as it will take you.
  • 相关阅读:
    IntelliJ IDEA如何导入Gradle项目
    C#对图像像素处理的三种方式
    用BitBlt截取整屏后半透明窗口不能显示的解决办法
    Kestrel gRPC
    aspnetcore datetime json格式化
    netcore rabbitMq
    Nginx 1.8 单元控制文件
    mysql 单元控制文件
    redis 单元控制文件
    devtoolset对应gcc的版本
  • 原文地址:https://www.cnblogs.com/jianpanaq/p/10274648.html
Copyright © 2020-2023  润新知