spring boot

SpringBoot学习笔记四:日志

2018-07-03  本文已影响22人  fulgens

Spring Boot官方文档日志部分
https://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#boot-features-logging

Spring Boot使用Commons Logging进行所有内部日志记录,但开放了底层日志实现 leaves the underlying log implementation open。为Java Util LoggingLog4J2Logback提供了默认配置 。在每种情况下,记录器都预先配置为使用控制台输出,并提供可选的文件输出。

默认情况下,如果使用“Starters”,则使用 Logback进行日志记录。还包括适当的Logback路由,以确保使用Java Util Logging,Commons Logging,Log4J或SLF4J的依赖库全部正常工作。

Java有很多可用的日志框架。如果对上面的列表感到困惑也不用担心。一般来说,使用 SpringBoot 默认的 Logback 就可以了。

日志格式

Spring Boot的默认日志输出类似于以下示例:

2014-03-05 10:57:51.112  INFO 45469 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/7.0.52
2014-03-05 10:57:51.253  INFO 45469 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2014-03-05 10:57:51.253  INFO 45469 --- [ost-startStop-1] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 1358 ms
2014-03-05 10:57:51.698  INFO 45469 --- [ost-startStop-1] o.s.b.c.e.ServletRegistrationBean        : Mapping servlet: 'dispatcherServlet' to [/]
2014-03-05 10:57:51.702  INFO 45469 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean  : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]

输出如下元素:

Logback 是没有 FATAL级别的日志,它将被映射到 ERROR

控制台输出

Spring Boot默认的日志配置打印日志到控制台。默认情况下,ERRORWARN以及INFO-级别的日志会被输出。可以在启动应用时加上--debug来启用"debug"模式。

$ java -jar myapp.jar --debug

也可在 application.properties 配置 debug=true

颜色编码

如果终端支持ANSI,则会使用彩色输出来提高可读性。可以设置 spring.output.ansi.enabled支持的值来覆盖自动检测。
定义在Enum AnsiOutput.Enabled中

日志级别与颜色对照表

Level Color
WARN Yellow
FATALERROR Red
INFODEBUGTRACE Green

如果想修改日志默认色值,可以通过使用 %clr 关键字转换。比如想使文本变为黄色 %clr(%d{yyyy-MM-dd HH:mm:ss.SSS}){yellow}。目前支持的颜色有(blue、cyan、faint、green、magenta、red、yellow)

文件输出

默认情况下,SpringBoot 仅将日志输出到控制台,不会写入到日志文件中去。如果除了控制台输出之外还想写日志文件,则需要在application.properties设置logging.filelogging.path 属性。

logging.file logging.path 示例 描述
(none) (none) 仅控制台输出日志
指定的文件 (none) my.log 输出日志到指定文件Names can be an exact location or relative to the current directory.
(none) 指定的目录 /var/log 将名为 spring.log 写入到指定目录中Names can be an exact location or relative to the current directory.

日志文件在达到 10MB 时进行切割,产生一个新的日志文件(如:spring.1.logspring.2.log),新的日志依旧输出到 spring.log 中去,默认情况下会记录 ERROR、WARN、INFO 级别日志。

logging.file.max-size: 限制日志文件大小
logging.file.max-history: 限制日志保留天数

日志级别

配置格式:logging.level.<logger-name>=<level>
如:

logging.level.root = WARN
logging.level.org.springframework.web = DEBUG
logging.level.org.hibernate = ERROR

#比如 mybatis sql日志
logging.level.org.mybatis = INFO
logging.level.mapper所在的包 = DEBUG

自定义日志配置

可以通过在类路径中包含适当的库来激活各种日志记录系统,并且可以通过在类路径的根目录中或通过logging.config指定配置文件位置。

由于日志服务一般都在ApplicationContext创建前就初始化了,它并不是必须通过Spring的配置文件控制。因此通过系统属性和传统的Spring Boot外部配置文件依然可以很好的支持日志控制和管理。

Logging System Customization
Logback logback-spring.xml, logback-spring.groovy, logback.xml, or logback.groovy
Log4j2 log4j2-spring.xml or log4j2.xml
JDK (Java Util Logging) logging.properties

Logback扩展配置

该扩展配置仅适用 logback-spring.xml 或者设置 logging.config 属性的文件,因为 logback.xml 加载过早,因此无法获取 SpringBoot 的一些扩展属性

使用扩展属性 springProfilespringProperty 让你的 logback-spring.xml 配置显得更有逼格,当别人还在苦苦挣扎弄logback-{profile}.xml的时候 你一个文件就搞定了...

springProfile

<springProfile> 标签使我们让配置文件更加灵活,它可以选择性的包含或排除部分配置。

<springProfile name="dev">
    <!-- 开发环境时激活 -->
</springProfile>

<springProfile name="dev,test">
    <!-- 开发,测试的时候激活-->
</springProfile>

<springProfile name="!prod">
    <!-- 当 "生产" 环境时,该配置不激活-->
</springProfile>

案例

<!-- 开发环境日志级别为DEBUG/并且开发环境不写日志文件 -->
<springProfile name="dev">
    <root level="DEBUG">
        <appender-ref ref="STDOUT"/>
    </root>
</springProfile>

<!-- 测试环境日志级别为INFO/并且记录日志文件 -->
<springProfile name="test">
    <root level="INFO">
        <appender-ref ref="FILE"/>
        <appender-ref ref="STDOUT"/>
    </root>
</springProfile>

springProperty

<springProperty> 标签可以让我们在 Logback 中使用 Spring Environment 中的属性。如果想在logback-spring.xml中回读 application.properties 配置的值时,这是一个非常好的解决方案

<!-- 读取 spring.application.name 属性来生成日志文件名
    scope:作用域
    name:在 logback-spring.xml 使用的键
    source:application.properties 文件中的键
    defaultValue:默认值
 -->
<springProperty scope="context" name="logName" source="spring.application.name" defaultValue="myapp.log"/>

<appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
    <file>logs/${logName}.log</file>
</appender>

Spring Boot默认关于logback配置

Spring Boot默认logback配置
base.xml
<?xml version="1.0" encoding="UTF-8"?>

<!--
Base logback configuration provided for compatibility with Spring Boot 1.1
-->

<included>
    <include resource="org/springframework/boot/logging/logback/defaults.xml" />
    <property name="LOG_FILE" value="${LOG_FILE:-${LOG_PATH:-${LOG_TEMP:-${java.io.tmpdir:-/tmp}}}/spring.log}"/>
    <include resource="org/springframework/boot/logging/logback/console-appender.xml" />
    <include resource="org/springframework/boot/logging/logback/file-appender.xml" />
    <root level="INFO">
        <appender-ref ref="CONSOLE" />
        <appender-ref ref="FILE" />
    </root>
</included>

defaults.xml

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

<!--
Default logback configuration provided for import, equivalent to the programmatic
initialization performed by Boot
-->

<included>
    <conversionRule conversionWord="clr" converterClass="org.springframework.boot.logging.logback.ColorConverter" />
    <conversionRule conversionWord="wex" converterClass="org.springframework.boot.logging.logback.WhitespaceThrowableProxyConverter" />
    <conversionRule conversionWord="wEx" converterClass="org.springframework.boot.logging.logback.ExtendedWhitespaceThrowableProxyConverter" />
    <property name="CONSOLE_LOG_PATTERN" value="${CONSOLE_LOG_PATTERN:-%clr(%d{${LOG_DATEFORMAT_PATTERN:-yyyy-MM-dd HH:mm:ss.SSS}}){faint} %clr(${LOG_LEVEL_PATTERN:-%5p}) %clr(${PID:- }){magenta} %clr(---){faint} %clr([%15.15t]){faint} %clr(%-40.40logger{39}){cyan} %clr(:){faint} %m%n${LOG_EXCEPTION_CONVERSION_WORD:-%wEx}}"/>
    <property name="FILE_LOG_PATTERN" value="${FILE_LOG_PATTERN:-%d{${LOG_DATEFORMAT_PATTERN:-yyyy-MM-dd HH:mm:ss.SSS}} ${LOG_LEVEL_PATTERN:-%5p} ${PID:- } --- [%t] %-40.40logger{39} : %m%n${LOG_EXCEPTION_CONVERSION_WORD:-%wEx}}"/>

    <logger name="org.apache.catalina.startup.DigesterFactory" level="ERROR"/>
    <logger name="org.apache.catalina.util.LifecycleBase" level="ERROR"/>
    <logger name="org.apache.coyote.http11.Http11NioProtocol" level="WARN"/>
    <logger name="org.apache.sshd.common.util.SecurityUtils" level="WARN"/>
    <logger name="org.apache.tomcat.util.net.NioSelectorPool" level="WARN"/>
    <logger name="org.eclipse.jetty.util.component.AbstractLifeCycle" level="ERROR"/>
    <logger name="org.hibernate.validator.internal.util.Version" level="WARN"/>
</included>

console-appender.xml

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

<!--
Console appender logback configuration provided for import, equivalent to the programmatic
initialization performed by Boot
-->

<included>
    <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>${CONSOLE_LOG_PATTERN}</pattern>
        </encoder>
    </appender>
</included>

file-appender.xml

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

<!--
File appender logback configuration provided for import, equivalent to the programmatic
initialization performed by Boot
-->

<included>
    <appender name="FILE"
        class="ch.qos.logback.core.rolling.RollingFileAppender">
        <encoder>
            <pattern>${FILE_LOG_PATTERN}</pattern>
        </encoder>
        <file>${LOG_FILE}</file>
        <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
            <fileNamePattern>${LOG_FILE}.%d{yyyy-MM-dd}.%i.gz</fileNamePattern>
            <maxFileSize>${LOG_FILE_MAX_SIZE:-10MB}</maxFileSize>
            <maxHistory>${LOG_FILE_MAX_HISTORY:-0}</maxHistory>
        </rollingPolicy>
    </appender>
</included>

自定义logback-spring.xml

以下是我自定义的logback配置,结合了Spring Boot对logback的扩展springProfilespringProperty。当设置spring.profiles.active=dev时日志级别为DEBUG,且只在控制台输出日志信息;当设置spring.profiles.active=testprod时日志级别为INFO,会在控制台和文件中输出日志信息,且对INFOERRORWARN级别的日志分别按天输出到不同的文件中去,如INFO级别日志输出文件名默认info.log但当文件大小达到10MB时会切分一次,产生新的日志文件eg: info-2018-07-01.0.loginfo-2018-07-01.1.loginfo-2018-07-01.2.log...

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

    <contextName>RestAPI</contextName>

    <!-- 控制台输出日志格式 -->
    <!--%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger - %msg%n-->
    <property name="CONSOLE_LOG_PATTERN" value="%d{yyyy-MM-dd HH:mm:ss.SSS} -%5p ${PID:- } --- [%15.15t] %-40.40logger{39} : %m%n"/>
    <!-- 文件日志输出格式 -->
    <property name="FILE_LOG_PATTERN" value="-%d{yyyy-MM-dd HH:mm:ss.SSS} -%5p ${PID:- } --- [%t] %-40.40logger{39} : %m%n"/>

    <logger name="org.apache.catalina.startup.DigesterFactory" level="ERROR"/>

    <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>${CONSOLE_LOG_PATTERN}</pattern>
            <charset>UTF-8</charset>
        </encoder>
    </appender>

    <property name="LOG_PATH" value="/Users/fulgens/log"/>
    <springProperty scope="context" name="appName" source="spring.application.name" defaultValue="myApp"/>

    <appender name="FILE_ERROR_LOG" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <file>${LOG_PATH}/${appName}/error.log</file>
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <fileNamePattern>${LOG_PATH}/${appName}/error-%d{yyyy-MM-dd}.%i.log</fileNamePattern>
            <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
                <maxFileSize>10MB</maxFileSize>
            </timeBasedFileNamingAndTriggeringPolicy>
        </rollingPolicy>
        <append>true</append>
        <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
            <pattern>${FILE_LOG_PATTERN}</pattern>
            <charset>UTF-8</charset>
        </encoder>
        <filter class="ch.qos.logback.classic.filter.LevelFilter">
            <level>ERROR</level>
            <onMatch>ACCEPT</onMatch>
            <onMismatch>DENY</onMismatch>
        </filter>
        <!--<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
            <level>ERROR</level>
        </filter>-->
    </appender>

    <appender name="FILE_WARN_LOG" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <file>${LOG_PATH}/${appName}/warn.log</file>
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <fileNamePattern>${LOG_PATH}/${appName}/warn-%d{yyyy-MM-dd}.%i.log</fileNamePattern>
            <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
                <maxFileSize>10MB</maxFileSize>
            </timeBasedFileNamingAndTriggeringPolicy>
        </rollingPolicy>
        <append>true</append>
        <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
            <pattern>${FILE_LOG_PATTERN}</pattern>
            <charset>UTF-8</charset>
        </encoder>
        <filter class="ch.qos.logback.classic.filter.LevelFilter">
            <level>WARN</level>
            <onMatch>ACCEPT</onMatch>
            <onMismatch>DENY</onMismatch>
        </filter>
    </appender>

    <appender name="FILE_INFO_LOG" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <file>${LOG_PATH}/${appName}/info.log</file>
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <fileNamePattern>${LOG_PATH}/${appName}/info-%d{yyyy-MM-dd}.%i.log</fileNamePattern>
            <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
                <maxFileSize>10MB</maxFileSize>
            </timeBasedFileNamingAndTriggeringPolicy>
        </rollingPolicy>
        <append>true</append>
        <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
            <pattern>${FILE_LOG_PATTERN}</pattern>
            <charset>UTF-8</charset>
        </encoder>
        <filter class="ch.qos.logback.classic.filter.LevelFilter">
            <level>INFO</level>
            <onMatch>ACCEPT</onMatch>
            <onMismatch>DENY</onMismatch>
        </filter>
    </appender>

    <!-- MyBatis sql日志 -->
    <logger name="com.example.springbootlogging.mapper" level="DEBUG" additivity="false"></logger>

    <!-- 开发环境日志级别为DEBUG/并且开发环境不写日志文件 -->
    <springProfile name="dev">
        <root level="DEBUG">
            <appender-ref ref="CONSOLE"/>
        </root>
    </springProfile>

    <!-- 测试环境日志级别为INFO/并且记录日志文件 -->
    <springProfile name="test">
        <root level="INFO">
            <appender-ref ref="FILE_ERROR_LOG"/>
            <appender-ref ref="FILE_WARN_LOG"/>
            <appender-ref ref="FILE_INFO_LOG"/>
            <appender-ref ref="CONSOLE"/>
        </root>
    </springProfile>

    <!-- 生产环境日志级别为INFO/并且记录日志文件 -->
    <springProfile name="prod">
        <root level="INFO">
            <appender-ref ref="FILE_ERROR_LOG"/>
            <appender-ref ref="FILE_WARN_LOG"/>
            <appender-ref ref="FILE_INFO_LOG"/>
            <appender-ref ref="CONSOLE"/>
        </root>
    </springProfile>

</configuration>

附Spring Boot所有Logging配置项

以下是我自定义的logback

# LOGGING 
logging.config= # Location of the logging configuration file. For instance, `classpath:logback.xml` for Logback.
logging.exception-conversion-word=%wEx # Conversion word used when logging exceptions.
logging.file= # Log file name (for instance, `myapp.log`). Names can be an exact location or relative to the current directory.
logging.file.max-history=0 # Maximum of archive log files to keep. Only supported with the default logback setup.
logging.file.max-size=10MB # Maximum log file size. Only supported with the default logback setup.
logging.level.*= # Log levels severity mapping. For instance, `logging.level.org.springframework=DEBUG`.
logging.path= # Location of the log file. For instance, `/var/log`.
logging.pattern.console= # Appender pattern for output to the console. Supported only with the default Logback setup.
logging.pattern.dateformat=yyyy-MM-dd HH:mm:ss.SSS # Appender pattern for log date format. Supported only with the default Logback setup.
logging.pattern.file= # Appender pattern for output to a file. Supported only with the default Logback setup.
logging.pattern.level=%5p # Appender pattern for log level. Supported only with the default Logback setup.
logging.register-shutdown-hook=false # Register a shutdown hook for the logging system when it is initialized.
上一篇 下一篇

猜你喜欢

热点阅读