Super detailed log configuration of springboot based on logback

Time:2020-2-11

Preface

There are several log frameworks in Java Web, such as: logback, log4j, log4j2 (slj4f is not a log framework, it is equivalent to defining a specification, which can be called with slj4f). The highest performance should be logback, and spring boot uses logback logs by default, so this article will explain the log configuration scheme of logback in detail.

The main contents of this article are as follows:

• composition of logback configuration file
• how to output logs to files
How to segment logs by time and size
How to make a log file with only one log level
How to output the logs under the specified package to the specified log file

Simple use

If complex log configuration is not required, simply set the log printing level, and the printing mode can be directlyapplication.yml Configure.

By default, spring boot outputs the info level log to the console, does not write to the log file, and cannot perform complex configuration.  

Print to file

To output logs to a file, you can configure them in two ways:

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

Note: file and path cannot be configured at the same time. If path is configured at the same time, it will not take effect.

Print level control

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

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

*It can be a package name or a logger name, as follows:
logging:
 level:
  #Root log output at warn level
  root: info
  #All classes under this package are output at debug level
  com.example.log_demo.log1: warn

Logback detailed configuration

Next, we show how to configure log printing through a separate XML configuration file. Although spring boot is to eliminate XML, some complex functions still need to write XML. After using XMLapplication.yml Remove the configuration in to avoid conflicts

According to different log systems, the configuration file names are organized according to the specified rules and placed in the resources directory, which 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 file name: logging.config specifies the configuration file name:

logging.config=classpath:logging-config.xml

Spring boot officially recommends using the filename with – spring as your log configuration (for example, using logback-spring.xml instead oflogback.xml), named logback-spring.xml Spring boot can add some configuration items specific to spring boot.

Composition of logback configuration file

The root node < configuration > has five child nodes. Let’s introduce them one by one.

<root> node

The root node is a 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. The options are: trace, debug, info, warn, error, all, off.

The root node can contain 0 or more elements to add the appender. As follows:


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

The appender is also one of the child nodes, which will be explained later.

< contextname > node

Set the context name. The default is default. You can print the context name through% contextname. Generally, this property is not used.

< property > node

Used to define variables, easy to use. There are two properties: name, value. After defining variables, you can use ${} to use them. As follows:


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

< appender > node

Appender is used to format the node of log output, which is the most important. There are two properties:

• Name: name of the appender
• class: specify the output strategy, usually there are two types: console output and file output

Here is an example to illustrate how to use this:

1. Output to console / output log by time

<?xml version="1.0" encoding="UTF-8"?>
<configuration debug="false">
  <! -- set storage path variable -- >
  <property name="LOG_HOME" value="./log"/>

  <! -- console output appender -- >
  <appender name="console">
    <! -- set output format -- >
    <encoder>
      <! -- formatted output:%d for date,%thread for thread name,%-5level: Level 5 characters from left width%msg: log message,%n is line break -- >
      <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
      <! -- set encoding -- >
      <charset>UTF-8</charset>
    </encoder>
  </appender>

  <! -- file output, time window scrolling -- >
  <appender name="timeFileOutput">
    <! -- log name, specify the latest file name, and use filenamepattern -- >
    <File>${LOG_HOME}/timeFile/out.log</File>
    <! -- File scrolling mode -- >
    <rollingPolicy>
      <! -- the file name of log file output. You can set the file type to GZ and enable file compression -- >
      <FileNamePattern>${LOG_HOME}/timeFile/info.%d{yyyy-MM-dd}.%i.log.gz</FileNamePattern>
      <! -- log file retention days -- >
      <MaxHistory>30</MaxHistory>
      <! -- split by size -- >
      <timeBasedFileNamingAndTriggeringPolicy>
        <maxFileSize>10MB</maxFileSize>
      </timeBasedFileNamingAndTriggeringPolicy>
    </rollingPolicy>

    <! -- output format -- >
    <encoder>
      <! -- formatted output:%d for date,%thread for thread name,%-5level: Level 5 characters from left width%msg: log message,%n is line break -- >
      <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
      <! -- set encoding -- >
      <charset>UTF-8</charset>
    </encoder>

  </appender>

  <! -- specify the basic log output level -- >
  <root level="INFO">
    <! -- appender will be added to this logger -- >
    <appender-ref ref="console"/>
    <appender-ref ref="timeFileOutput"/>
  </root>
</configuration>

1. Set to output only a single level

In the appender, set the filter sub node, filter at the default level, configure onmatch, and onmismatch can output only a single level

<appender ...>
  <filter>
    <level>INFO</level>
    <! -- accept match -- >
    <onMatch>ACCEPT</onMatch>
    <! -- reject unmatched -- >
    <onMismatch>DENY</onMismatch>
  </filter>
</appender>

< logger > node

constitute

This node is used to set the log printing level of a package or a specific class, and to specify < appender >. It has the following three properties:

• Name: required. Used to specify a package or a specific class constrained by this logger
• level: optional. Set the print level. The default is the level of root.
• addtivity: optional. Whether to pass the printing information to the superior logger (that is, the root node). The default is true.

Examples of use are as follows:

1. No level or appender specified

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

2. Specify the level, not the appender

<! -- control the printing of 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 the level and the appender

<! -- control the printing of classes under com.example.service, and use console to print the warn level log -- >
<! -- the addtivity is set because the appender is specified here. If it is passed up again, it will be printed again by the appender under root -- >
<logger name="com.example.service" level="WARN" addtivity="false">
  <appender-ref ref="console">
</logger>

The log under the specified package can be printed to the specified file by specifying the appender.

Multi environment log output

By setting the filename to – spring end, you can configure the logger in different environments, as shown in the following example:

<configuration>
  <! -- test environment + development environment. Multiple are 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>

You can also switch the above logger printing settings by configuring spring.profiles.active

End

Log printing can be very complex. Here is just a description of the commonly used logback configuration. For the code, see GitHub

summary

The above is the super detailed log configuration of springboot based on logback introduced by Xiaobian to you. I hope it will help you. If you have any questions, please leave me a message and Xiaobian will reply to you in time. Thank you very much for your support of the developepaer website!
If you think this article is helpful to you, welcome to reprint, please indicate the source, thank you!