SpringBoot整合日志框架

SpringBoot日志框架

  1. 移除默认日志

    <dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter</artifactId>
          <exclusions>
          <!--去除日志依赖-->
            <exclusion>
                  <groupId>org.springframework.boot</groupId>
                  <artifactId>spring-boot-starter-logging</artifactId>
              </exclusion>
            </exclusions>
    </dependency>
    
  2. 添加日志框架依赖

    <!--引入日志框架 抽象层与实现层-->
    <dependency>
          <groupId>org.slf4j</groupId>
          <artifactId>slf4j-api</artifactId>
          <version>1.7.21</version>
    </dependency>
    <dependency>
          <groupId>org.slf4j</groupId>
          <artifactId>slf4j-log4j12</artifactId>
          <version>1.7.21</version>
    </dependency>
    
  3. 创建log4j.properties并且放置在资源文件目录src/main/resources/log4j.properties

    log4j.rootLogger=DEBUG,stdout
    #log4j.rootLogger=DEBUG,stdout,file
    log4j.additivity.org.apache=true
    
    log4j.appender.stdout=org.apache.log4j.ConsoleAppender
    log4j.appender.stdout.threshold=INFO
    log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
    log4j.appender.stdout.layout.ConversionPattern=%-5p %c{1}:%L - %m%n
    
    # 将日志写入到指定文件中
    #log4j.appender.file=org.apache.log4j.DailyRollingFileAppender
    #log4j.appender.file.layout=org.apache.log4j.PatternLayout
    #log4j.appender.file.DatePattern='.'yyyy-MM-dd-HH-mm
    #log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
    #log4j.appender.file.Threshold=INFO
    #log4j.appender.file.append=true
    #log4j.appender.file.File=/workspaces/logs/foodie-api/imooc.log
    
  4. 在application.yml中添加打印MyBatis logger的配置

    mybatis:
      type-aliases-package: com.imooc.pojo
      mapper-locations: classpath:mapper/*.xml
      configuration:
        log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
    
  5. 在Controller中打印日志

    public static final Logger log = LoggerFactory.getLogger(xxxx.class);
    
     log.error("====== 执行结束,耗时:{} 毫秒 ======",takeTime);
     log.warn("====== 执行结束,耗时:{} 毫秒 ======",takeTime);
     log.info("====== 执行结束,耗时:{} 毫秒 ======",takeTime);
    
上一篇:如何使用slf4j ???


下一篇:spark日志输出