Spring boot logging

Posted xiaoduup

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Spring boot logging相关的知识,希望对你有一定的参考价值。

Spring boot logging

文章目录

源码

源码链接 https://gitee.com/mayun_xiaodu/spring-boot-all

上一节 Spring boot 配置文件读取和yaml结构

Spring boot 配置文件读取和yaml结构


首先我们搭一个web工程,集成spring-boot-starter-web;spring-boot-starter-web中依赖了spring-boot-starter-logging;
启动springboot

springboot 启动日志

springboot 提供的默认输出日志


 .   ____          _            __ _ _
/\\\\ / ___'_ __ _ _(_)_ __  __ _ \\ \\ \\ \\
( ( )\\___ | '_ | '_| | '_ \\/ _` | \\ \\ \\ \\
\\\\/  ___)| |_)| | | | | || (_| |  ) ) ) )
 '  |____| .__|_| |_|_| |_\\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot ::        (v2.1.6.RELEASE)

2021-03-29 09:55:06.451  INFO 80640 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
2021-03-29 09:55:06.473  INFO 80640 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2021-03-29 09:55:06.473  INFO 80640 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.21]
2021-03-29 09:55:06.566  INFO 80640 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2021-03-29 09:55:06.566  INFO 80640 --- [           main] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 1249 ms
2021-03-29 09:55:06.753  INFO 80640 --- [           main] o.s.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService 'applicationTaskExecutor'
2021-03-29 09:55:06.882  INFO 80640 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''

自定义logging

(这里使用 slf4j + logback 进行示例)

1.配置文件中设置日志参数

logging:
  level:
    root: info   # 配置root 的级别
    com.xiaodu.springboot.logging: warn # 配置具体包下的日志级别
  file:
    max-size: 10KB
    max-history: 7
  path: logging-logs
  pattern:
    ## %d日期格式  %level 日志级别  %t 线程  %loggerlength logger名 %m 日志内容 %L 日志输出的行数, %n 换行;
    console: '%dyyyy-MM-dd HH:mm:ss.SSS [%level] [%15t] %logger20 => %m Line: %L%n'

代码中输出日志

  // 进行日志输出
        log.trace("trace => ", "springboot-logging");
        log.debug("debug => ", "springbooot-logging");
        log.info("info => ", "springboot-logging");
        log.warn("warn => ", "springboot-logging");
        log.error("error => ", "springboot-logging");

在配置文件中设置了日志的root 为info级别, com.xiaodu.springboot.logging 包下的logger为warn级别;日志文件最大10KB, 保存7天;存放路径为 loggin-logs目录下;并自定义了日志输出的console格式
启动程序

  .   ____          _            __ _ _
 /\\\\ / ___'_ __ _ _(_)_ __  __ _ \\ \\ \\ \\
( ( )\\___ | '_ | '_| | '_ \\/ _` | \\ \\ \\ \\
 \\\\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.1.6.RELEASE)

2021-03-29 11:15:52.700 [INFO] [           main] o.s.b.w.e.t.TomcatWebServer => Tomcat initialized with port(s): 8080 (http) Line: 90
2021-03-29 11:15:52.719 [INFO] [           main] o.a.c.c.StandardService => Starting service [Tomcat] Line: 173
2021-03-29 11:15:52.719 [INFO] [           main] o.a.c.c.StandardEngine => Starting Servlet engine: [Apache Tomcat/9.0.21] Line: 173
2021-03-29 11:15:52.799 [INFO] [           main] o.a.c.c.C.[.[.[/] => Initializing Spring embedded WebApplicationContext Line: 173
2021-03-29 11:15:52.799 [INFO] [           main] o.s.w.c.ContextLoader => Root WebApplicationContext: initialization completed in 1360 ms Line: 283
2021-03-29 11:15:52.938 [INFO] [           main] o.s.s.c.ThreadPoolTaskExecutor => Initializing ExecutorService 'applicationTaskExecutor' Line: 171
2021-03-29 11:15:53.069 [INFO] [           main] o.s.b.w.e.t.TomcatWebServer => Tomcat started on port(s): 8080 (http) with context path '' Line: 202
2021-03-29 11:15:53.072 [WARN] [           main] c.x.s.l.LoggingApplication => warn => springboot-logging Line: 28
2021-03-29 11:15:53.074 [ERROR] [           main] c.x.s.l.LoggingApplication => error => springboot-logging Line: 29

2.使用日志文件配置logging
resources 下创建 logback.xml
具体的java 日志规范这里不再阐述。
创建一个简单的logback.xml; 配置了 root, logger, layout, appender

<?xml version="1.0" encoding="UTF-8"?>

<configuration debug="false">

    <property name="APP_NAME" value = "springboot-logging-test"/>
<!--输出到控制台-->
    <appender name = "console" class="ch.qos.logback.core.ConsoleAppender">
        <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
            <pattern>$APP_NAME -- %dyyyy-MM-dd HH:mm:ss.SSS [%level] [%15t] %logger20 => %m Line: %L%n</pattern>
        </encoder>
    </appender>
<!--输出到文件-->
    <appender name="file" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <File>springboot-log-test/$APP_NAME_stdout.log</File>
<!-- 配置文件滚动策略 -->
        <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<!--            滚动生成的文件名称-->
            <FileNamePattern>springboot-log-test/$APP_NAME_stdout.%dyyyy-MM-dd-%i.log</FileNamePattern>
<!--      最大保存7天的日志      -->
            <maxHistory>7</maxHistory>
<!--         日志文件超过5kb后,生成一个新的文件记录日志-->
            <MaxFileSize>5KB</MaxFileSize>
        </rollingPolicy>
        <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
            <pattern>$APP_NAME -- %dyyyy-MM-dd HH:mm:ss.SSS [%level] [%15t] %logger20 => %m Line: %L%n</pattern>
        </encoder>
    </appender>
    <logger name ="com.xiaodu.springboot.logging">
        <level value = "debug"/>
    </logger>

    <root>
        <level value="info"/>
        <appender-ref ref="console"/>
        <appender-ref ref="file"/>
    </root>
</configuration>


以上配置后我们打印的日志

springboot-logging-test -- 2021-03-29 12:07:54.944 [DEBUG] [           main] c.x.s.l.LoggingApplication => Running with Spring Boot v2.1.6.RELEASE, Spring v5.1.8.RELEASE Line: 53
springboot-logging-test -- 2021-03-29 12:07:54.945 [INFO] [           main] c.x.s.l.LoggingApplication => No active profile set, falling back to default profiles: default Line: 646
springboot-logging-test -- 2021-03-29 12:07:56.164 [INFO] [           main] o.s.b.w.e.t.TomcatWebServer => Tomcat initialized with port(s): 8080 (http) Line: 90
springboot-logging-test -- 2021-03-29 12:07:56.223 [INFO] [           main] o.a.c.h.Http11NioProtocol => Initializing ProtocolHandler ["http-nio-8080"] Line: 173
springboot-logging-test -- 2021-03-29 12:07:56.229 [INFO] [           main] o.a.c.c.StandardService => Starting service [Tomcat] Line: 173
springboot-logging-test -- 2021-03-29 12:07:56.229 [INFO] [           main] o.a.c.c.StandardEngine => Starting Servlet engine: [Apache Tomcat/9.0.21] Line: 173
springboot-logging-test -- 2021-03-29 12:07:56.299 [INFO] [           main] o.a.c.c.C.[.[.[/] => Initializing Spring embedded WebApplicationContext Line: 173
springboot-logging-test -- 2021-03-29 12:07:56.299 [INFO] [           main] o.s.w.c.ContextLoader => Root WebApplicationContext: initialization completed in 1289 ms Line: 283
springboot-logging-test -- 2021-03-29 12:07:56.461 [INFO] [           main] o.s.s.c.ThreadPoolTaskExecutor => Initializing ExecutorService 'applicationTaskExecutor' Line: 171
springboot-logging-test -- 2021-03-29 12:07:56.561 [INFO] [           main] o.a.c.h.Http11NioProtocol => Starting ProtocolHandler ["http-nio-8080"] Line: 173
springboot-logging-test -- 2021-03-29 12:07:56.582 [INFO] [           main] o.s.b.w.e.t.TomcatWebServer => Tomcat started on port(s): 8080 (http) with context path '' Line: 202
springboot-logging-test -- 2021-03-29 12:07:56.584 [INFO] [           main] c.x.s.l.LoggingApplication => Started LoggingApplication in 1.972 seconds (JVM running for 2.929) Line: 59
springboot-logging-test -- 2021-03-29 12:07:56.586 [DEBUG] [           main] c.x.s.l.LoggingApplication => debug => springbooot-logging Line: 26
springboot-logging-test -- 2021-03-29 12:07:56.586 [INFO] [           main] c.x.s.l.LoggingApplication => info => springboot-logging Line: 27
springboot-logging-test -- 2021-03-29 12:07:56.587 [WARN] [           main] c.x.s.l.LoggingApplication => warn => springboot-logging Line: 28
springboot-logging-test -- 2021-03-29 12:07:56.587 [ERROR] [           main] c.x.s.l.LoggingApplication => error => springboot-logging Line: 29

日志文件保存路径

也可以直接生成压缩包, 修改文件后缀即可

 <FileNamePattern>springboot-log-test/$APP_NAME_stdout.%dyyyy-MM-dd-%i.log.gz</FileNamePattern>

springboot 对logback中的扩展支持

resources 下创建 logback-spring.xml

(springboot 优先加载 “logback-test.groovy”, “logback-test.xml”,
“logback.groovy”, “logback.xml”, 若classpath下没有发现以上文件,则加载
“logback-test-spring.groovy”, “logback-test-spring.xml”,
“logback-spring.groovy”, “logback-spring.xml” 日志配置文件)
我们现在使用logback-spring.xml, 然后 把 logback.xml 临时改下名称 logback-temp.xml或者删除也可以

logback-spring.xml
spring 特有的日志标签

  • springProperty 获取spring配置信息
  • springProfile 根据spring.profile.active 进行不同的环境使用不同的日志配置
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<!--获取spirng配置信息-->
    <springProperty name = "AAA" source = "spring.application.name"/>

    <appender name = "console" class = "ch.qos.logback.core.ConsoleAppender">
        <Target>System.out</Target>
        <encoder>
            <pattern>$AAA%dyyyy-MM-dd HH:mm:ss.SSS [%level] [%t] %c20 => %m%n</pattern>
        </encoder>
    </appender>
<!--根据spring.profiles.active 指定环境 使用不同logger进行不同环境中的不同级别日志打印-->
    <springProfile name = "dev | test">
        <logger name = "com.xiaodu.springboot.logging">
            <level value = "debug"/>
        </logger>
    </springProfile>

    <springProfile name = "prod">
        <logger name = "com.xiaodu.springboot.logging">
            <level value = "warn"/>
        </logger>
    </springProfile>
    <root>
        <level value="info"/>
        <appender-ref ref="console"/>
    </root>
</configuration>
 上述是一个简单的日志配置文件; springboot 提供了 springProperty 属性进行获取环境配置信息,
   springprofile 进行获取 spring.profiles.active信息;根据不同的开发,测试,生成环境进行不同的日志输出

控制台日志颜色输出

logback 自带的日志显示

%color(日志内容) 表示
示例:

  1. %red(%t)
  2. %blue(%logger)

    完整示例
    <pattern>%magenta($AAA) – %dyyyy-MM-dd HH:mm:ss.SSS %red([%5level]) %blue([%10t]) %cyan(%40logger39) : %yellow(%m) %n</pattern>

springboot 提供的 %clr
格式: %clr(日志内容)color; 不指定color时可以根据日志的级别自动显示颜色
springboot 提供了日志颜色转换器,ColorConverter

<!--   日志颜色转换器 -->
    <conversionRule conversionWord="clr" spring-boot中如何配置tomcat访问日志的位置和名称?

Spring Boot 加载不同名称的 log4j2.xml log4j2-app.xml

已部署的 Spring Boot 应用程序的 spring-boot-logger.log 文件位置

spring boot logging.path 不生效,不生成日志文件

spring boot自定义log4j2日志文件

Spring boot启动后没有生成日志文件问题排错