Super detailed log configuration of springboot (based on logback)

Time:2019-10-23

Super detailed log configuration of springboot (based on logback)

preface

There are several logging frameworks under the Java web, such as: logback, log4j, log4j2 (slj4f is not a logging framework, it is equivalent to defining the specification, the implementation of this specification logging framework can be called with slj4f). The highest performance should be logback, and springboot defaults to logback as well, so this article will cover the log configuration scheme for logback in more detail.

The main content of this article is as follows:

  • The composition of the logback configuration file
  • How do I output the log to a file
  • How to split logs by time and size
  • How do you keep only one log level in a log file
  • How do I export the log under the specified package to the specified log file

Simple to use

If complex log configuration is not required, simply set the log print level, which can be configured directly in application.yml.

By default, Spring Boot outputs info-level logs to the console, does not write to log files, and cannot be configured in a complex way.

<!– more –>

Print to file

To output the log to a file, you can configure it in two ways:

logging:
  Configure the output log filename, with a path
  #  file: out.log
  Configure the log storage path with the log file name: spring.log
  path: ./log
  file:
    Set the log file size
    max-size: 10MB

Pay attention to:file and path cannot be configured at the same time, if configured at the same timepathIt doesn’t work.

Print level control

The level of log printing can be controlled by configuration. The format is as follows:

logging.level.*=TRACE/DEBUG/INFO/...

* can be a package name or a Logger name, as follows:

logging:
  level:
    The # root log is output at the WARN level
    root: info
    All classes under this package are output at the DEBUG level
    com.example.log_demo.log1: warn

Logback details configuration

The following shows how to configure log printing through a separate XML configuration file. Although springboot is meant to kill XML, some of the more complex features still require XML to be written. After using XML, remove the configuration in application.yml to avoid conflicts.

According to the different logging system, according to the specified rules to organize the configuration file name, and placed in the resources directory, can be automatically loaded by spring boot:

  • Logback:logback-spring.xml, logback-spring.groovy, logback.xml, logback.groovy
  • Log4j: log4j-spring.properties, log4j-spring.xml, log4j.properties, log4j.xml
  • Log4j2: log4j2-spring.xml, log4j2.xml
  • JDK (Java Util Logging): logging.properties

To customize the configurable filename:logging.configSpecify profile name:

logging.config=classpath:logging-config.xml

Spring Boot officially recommends using a file name with -spring as your log configuration (for example, logback-spring.xml instead of logback.xml), which is named logback-spring.xml.

The composition of the logback configuration file

The root node<configuration>There are five child nodes, which are described below.

<root>node

Root node is the required node, which is used to specify the most basic log output level. There is only one level attribute, which is used to set the print level. It can be selected as follows:TRACE,DEBUG,INFO,WARN,ERROR,ALL,OFF

The root node can contain 0 or more elements that willappenderAdd in. As follows:

<root level="debug">
 <appender-ref ref="console" />
 <appender-ref ref="file" />
</root>

Appender is also one of the child nodes, which is explained later.

<contextName>node

Sets the context name, which defaults todefaultby%contextNameTo print the context name. This property is generally not used.

<property>node

Used to define variables, easy to use. There are two attributes: name,value. After the variable is defined, it can be used${}To use variables. As follows:

<property name="path" value="./log"/>
<property name="appname" value="app"/>

<appender>node

One of the most important is the node appender USES to format the log output. There are two properties:

  • Name: this appender is named
  • Class: specifies an output strategy, usually of two types: console output and file output

Here’s an example of how this works:

  1. Output to console/output log by time
<?xml version="1.0" encoding="UTF-8"?>
<configuration debug="false">
    <! -- set the storage path variable -->
    <property name="LOG_HOME" value="./log"/>

    <! Console output appender- >
    <appender name="console" class="ch.qos.logback.core.ConsoleAppender">
        <! -- set the output format -->
        <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
            <! -- format output: %d for date, %thread for thread name, %-5level: 5 characters width % MSG: log message from left, %n for newline ->
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
            <! -- set the code -->
            <charset>UTF-8</charset>
        </encoder>
    </appender>

    <! File output, time window scroll ->
    <appender name="timeFileOutput" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <! -- log name, specifying the latest filename, and other filenames using FileNamePattern -->
        <File>${LOG_HOME}/timeFile/out.log</File>
        <! -- file scroll mode -->
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <! -- filename of log file output, file type can be set to gz, turn on file compression -->
            <FileNamePattern>${LOG_HOME}/timeFile/info.%d{yyyy-MM-dd}.%i.log.gz</FileNamePattern>
            <! -- log file retention days -- ->
            <MaxHistory>30</MaxHistory>
            <! -- split the same day by size -->
            <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
                <maxFileSize>10MB</maxFileSize>
            </timeBasedFileNamingAndTriggeringPolicy>
        </rollingPolicy>

        <! -- output format -->
        <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
            <! -- format output: %d for date, %thread for thread name, %-5level: 5 characters width % MSG: log message from left, %n for newline ->
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
            <! -- set the code -->
            <charset>UTF-8</charset>
        </encoder>

    </appender>

    <! -- specifies the underlying log output level -->
    <root level="INFO">
        <! Appender to this loger- >
        <appender-ref ref="console"/>
        <appender-ref ref="timeFileOutput"/>
    </root>
</configuration>
  1. Set to output only a single level

The appender has a filter sub node that filters at the default level, and onMatch, which mismatches, outputs a single level

<appender ...>
    <filter class="ch.qos.logback.classic.filter.LevelFilter">
        <level>INFO</level>
        <! -- accept match -- ->
        <onMatch>ACCEPT</onMatch>
        <! -- reject mismatch -->
        <onMismatch>DENY</onMismatch>
    </filter>
</appender>

<logger>node

Constitute a

This node is used to set the log print level for a package or a specific class, and to specify<appender>, has the following three attributes:

  • Name: must be. To specify a package or a specific class that is bound to this loger
  • Level: optional. Set the print level. The default is the level root.
  • Addtivity: optional. Whether print information is passed to the superior loger(that is, root node). The default value is true.

Examples are as follows:

  1. No level, no appender
<! -- control the printing of classes under com.example.service, using root's level and appender -->
<logger name="com.example.service"/>

2. Specified level, no appender is specified

<! Control the printing of the classes under com.example.service and use root's appender to print the warn level log ->
<logger name="com.example.service" level="WARN"/>

3. Specify level and append

<! Control the printing of the classes under com.example.service and use the console to print the warn level log ->
<! Addtivity is set because the appender has already been specified and if passed up it will be reprinted by the appender under root ->
<logger name="com.example.service" level="WARN" addtivity="false">
    <appender-ref ref="console">
</logger>

By specifying an appender you can print the log under the specified package to the specified file.

Multi-environment log output

Logger can be configured in a separate environment by setting the file name -spring end, as shown in the following example:

<configuration>
    <! - test environment + development environment. Multiple separated by commas. ->
    <springProfile name="test,dev">
        <logger name="com.example.demo.controller" level="DEBUG" additivity="false">
            <appender-ref ref="console"/>
        </logger>
    </springProfile>
    <! -- production environment
    <springProfile name="prod">
        <logger name="com.example.demo" level="INFO" additivity="false">
            <appender-ref ref="timeFileOutput"/>
        </logger>
    </springProfile>
</configuration>

By configuringspring.profiles.activeYou can also toggle the logger print Settings above

The end of the

Log printing can be complex, but here is just a description of the common logback configuration, see github for the code

This article was originally published in:http://www.tapme.top/blog/detail/2019-03-21-10-38

Recommended Today

Database lock (notes)

Introduction MyISAMTransaction is not supported. What is the difference between MyISAM and InnoDB in terms of locks MyISAMTable level lock is used by default, row level lock is not supported. InnoDBRow level locks are used by default, and table level locks are also supported. Read lock / shared lock: othersessionCan read, but can’t write. Write […]