preface

There are several logging frameworks available on the Java Web, such as LogBack, Log4j, and log4j2 (SLJ4F is not a logging framework, it defines the specification, and the logging framework that implements this specification can be invoked using SLJ4F). Springboot uses logback logs by default, so this article will explain how to configure logback logs in detail.

The main contents of this paper are as follows:

  • Composition of the LogBack configuration file
  • How do I output logs to a file
  • How to split logs by time and size
  • How do I make a log file have only one log level
  • How do I output logs from a specified package to a specified log file

Simple to use

If complex log configuration is not required, you can set the log printing level and the printing mode in application.yml.

By default, Spring Boot outputs info-level logs to the console, not to log files, and not to complex configurations.

Print to a file

To export logs to a file, you can do the following two configurations:

logging:
  Configure the output log file name, can have a path
  # file: out.log
  Log file name: spring.log
  path: ./log
  file:
    Set the log file size
    max-size: 10MB
Copy the code

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

Print level control

You can configure the log printing level in the following format:

logging.level.*=TRACE/DEBUG/INFO/...
Copy the code

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

logging:
  level:
    # root logs are output at WARN level
    root: info
    All classes in this package are output at DEBUG level
    com.example.log_demo.log1: warn
Copy the code

Logback Detailed configuration

Next, I show you how to configure log printing through a separate XML configuration file. Although SpringBoot is intended to eliminate XML, some complex functions still require XML writing. After using XML, remove the configuration in application.yml to avoid conflicts.

Spring Boot can automatically load configuration files by organizing them according to the specified rules according to different logging systems and placing them in the resources directory:

  • 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

Configurable file name you want to customize: logging.config Specifies the configuration file name:

logging.config=classpath:logging-config.xml
Copy the code

Spring Boot officially recommends that you use a -spring file name for your log configuration (e.g. Logback-spring. XML instead of logback.xml). Spring Boot can add some Spring Boot-specific configuration items to it (mentioned below).

Composition of the LogBack configuration file

The root node < Configuration > has five child nodes, which are described below.

<root>node

Root node is selected, which is used to specify the most basic level of log output, there is only one level attributes, used to set the level of print, optional is as follows: the TRACE, DEBUG, INFO, WARN, ERROR, ALL, OFF.

The root node can have zero or more elements to which an appender can be added. As follows:

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

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

<contextName>node

Set the contextName. Default is default. The name of the context can be printed with %contextName.

<property>node

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

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

<appender>node

The appender is used to format the node for log output, which is the most important. There are two properties:

  • Name: Name of the appender
  • Class: Specifies the output policy. There are usually two types: console output and file output

Here’s an example of how this works:

  1. Output to console/output logs 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" class="ch.qos.logback.core.ConsoleAppender">
        <! Set the output format -->
        <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
            <! Format output: %d indicates the date, %thread indicates the thread name, %-5level indicates the level of 5 characters from the left. % MSG indicates the log message, %n indicates the newline character.
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
            <! -- Set code -->
            <charset>UTF-8</charset>
        </encoder>
    </appender>

    <! File output, time window scroll -->
    <appender name="timeFileOutput" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <! -- Log name, specify the latest file name, other file names use FileNamePattern -->
        <File>${LOG_HOME}/timeFile/out.log</File>
        <! -- File scroll mode -->
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <! -- Log file output file name, the file type can be set to gz, enable 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 indicates the date, %thread indicates the thread name, %-5level indicates the level of 5 characters from the left. % MSG indicates the log message, %n indicates the newline character.
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
            <! -- Set code -->
            <charset>UTF-8</charset>
        </encoder>

    </appender>

    <! -- Specify the base log output level -->
    <root level="INFO">
        <! -- Appender will be appended to this loger-->
        <appender-ref ref="console"/>
        <appender-ref ref="timeFileOutput"/>
    </root>
</configuration>
Copy the code
  1. Sets the output to a single level

In appender, set the filter child node to the default level and configure onMatch and onMismatch to output only a single level

<appender .>
    <filter class="ch.qos.logback.classic.filter.LevelFilter">
        <level>INFO</level>
        <! -- Accept match -->
        <onMatch>ACCEPT</onMatch>
        <! -- Reject unmatched -->
        <onMismatch>DENY</onMismatch>
    </filter>
</appender>
Copy the code

<logger>node

Constitute a

This object sets the log printing level for a package or class and specifies

. It has three properties:

  • Name: must be. Used to specify a package or a concrete class that is bound by this loger
  • Level: Optional. Sets the print level. The default level is root.
  • Addtivity: optional. Whether to send printed information to the parent loger(root node). The default is true.

The following is an example:

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

2. Specify the level without specifying an appender

<! -- Controls the printing of classes under com.example.service, using root's appender to print warn logs -->
<logger name="com.example.service" level="WARN"/>
Copy the code

3. Specify the level and appender

<! -- Control the printing of classes under com.example.service, use console to print warn logs -->
<! Addtivity is set because an appender is already configured, and if passed up it will be printed again by the root appender.
<logger name="com.example.service" level="WARN" addtivity="false">
    <appender-ref ref="console">
</logger>
Copy the code

You can print logs from the specified package to the specified file by specifying an appender.

Multi-environment log output

Logger can be configured separately by setting the file name to end with -spring, as shown in the following example:

<configuration>
    <! -- Test environment + development environment. Separate multiple entries with 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>
Copy the code

It is also possible to switch logger printing Settings above by configuring spring.profiles.active

The end of the

Log printing can be complex, but this is just an illustration of the common logback configuration. See github for the code

Original published in this article: www.tapme.top/blog/detail…