Logging is a must for any project, and Spring Boot naturally supports it.

As shown in the figure, spring-boot-starter-logging is a logging solution provided by Spring. It uses SLF4J Logging facade framework as interface masking layer and supports logback, Log4j2, JUL(Java Util Logging) and other Logging implementation frameworks

For details about the logging facade framework and logging implementation framework, see Logging Framework in Java Ecology

The following is based on Spring Boot 2.2.2f

Logging

Spring Boot Logging provides default configurations for Java Util Logging (JUL), Log4J2, and Logback. Logs are exported to the console by default, but you can also configure them to be exported to a file

Usually, you don’t need to change any Settings, and Spring Boot defaults let the logging framework work.

Log format

By default, Spring Boot outputs logs in the following formats

The 2019-03-05 10:57:51. 45469-112 the INFO [main] org. Apache. Catalina. Core. StandardEngine: Starting the Servlet Engine: Apache Tomcat/7.0.52 2019-03-05 10:57:51.253 INFO 45469 -- [ost-startstop-1] O.A.C.C.C. [Tomcat].[/] : Apache Tomcat/7.0.52 2019-03-05 10:57:51.253 INFO 45469 -- [ost-startStop-1] O.A.C.C.C. Initializing Spring Embedded WebApplicationContext 2019-03-05 10:57:51.253 INFO 45469 -- [ost-startstop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 1358 msCopy the code

In this order

  • Yyyy-mm-dd hh: MM: SS, the timestamp is in SSS format
  • Log level. Possible values include ERROR, WARN, INFO, DEBUG, and TRACE
  • PID(Process NUMBER)
  • Separators (-)
  • [Current thread name]
  • Classpath, usually abbreviated
  • Log information
Logback does not have FATAL, which is mapped to ERRORCopy the code

Output to console

By default, messages of the ERROR, WARN, and INFO levels are logged and output to the console.

If you want to enable debug level messages, you need to set debug=true in application.properties

With Debug enabled, some core loggers (Hibernate, Spring Boot) are configured to output more information. Not all DEBUG level messages are logged

color

If your terminal supports ANSI, Spring Boot tries to use color output to improve readability.

Configure the color by using the % CLR conversion word. In its simplest form, the converter colors the output based on the log level, as shown in the following example: % CLR (%5p)

Specifies the color of a log level

Level Color
FATAL Red
ERROR Red
WARN Yellow
INFO Green
DEBUG Green
TRACE Green

You can also specify the color manually, for example, to specify the date as yellow % CLR (%d{YYYY-MM-DD HH: MM: ss.sss}){yellow}

Supported colors are

  • blue
  • cyan
  • faint
  • green
  • magenta
  • red
  • yellow

Output to file

By default, Spring Boot only prints logs to the console. If you also want to output to files, you need to configure logging.file.name or logging.file.path in application.properties

logging.file.name logging.file.path Description
No configuration No configuration Output to console
File name (absolute or relative path) No configuration Output to file
No configuration Absolute or relative path Writes spring.log to the specified directory

As with console output, only ERROR, WARN, and INFO messages are logged by default

Log files will scroll when they reach 10 MB, and you can configure logging.file.max-size to change the size limit. By default, archive log files are saved indefinitely. To limit this, set the logging.file.max-history property. If you want to further limit the total size of the log archive file, you need to set logging.file.total-size-cap. When the total size of the log archive exceeds this threshold, the log file will be deleted. If you want to clean up the log archive at application startup, you need to configure logging.file.clean-history-on-start

Logger level

All supported logging systems can be configured with logging.level.

=

in application.properties.

Where is the name of the logger, notably root, and the other logger names are generally full package names or class names

For example,

logging.level.root=warn
logging.level.org.springframework.web=debug
logging.level.org.hibernate=error
Copy the code

The recorder group

Set multiple related loggers into a group in application.properties so that they can be configured simultaneously

For example,

logging.group.tomcat=org.apache.catalina, org.apache.coyote, org.apache.tomcat
logging.level.tomcat=TRACE
Copy the code

Spring Boot includes the following predefined logger groups that you can use directly

Name Loggers
web org.springframework.core.codec.org.springframework.http.org.springframework.web.org.springframework.boot.actuate.endpoint.web.org.springframework.boot.web.servlet.ServletContextInitializerBeans
sql org.springframework.jdbc.core.org.hibernate.SQL.org.jooq.tools.LoggerListener

Custom log configuration

By providing the configuration file of the corresponding log system in the classpath, you can further customize the configuration of various log systems

Depending on your logging system, the following files will be loaded, in the following order if more than one configuration file exists

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

Spring recommends using the -spring suffix for logging configuration. If standard configuration names are used, Spring does not have full control over log initialization.

By configuring org. Springframework. Boot. Logging. LoggingSystem attribute to force a particular log system. Value is the fully qualified class name of the logging implementation. Setting it to None completely disables the Logging configuration for Spring Boot

Because logging is initialized before the ApplicationContext is created, it is not possible to control logging from @propertysources in the Spring @Configuration file. The only way to change the logging system or disable it completely is through system properties.Copy the code

To help with customization, some other properties have been moved from the Spring environment to system properties, as shown in the following table:

In the spring of the environment System property annotation
logging.exception-conversion-word LOG_EXCEPTION_CONVERSION_WORD The conversion word used when logging exceptions
logging.file.clean-history-on-start LOG_FILE_CLEAN_HISTORY_ON_START Whether to clear archive log files at startup (if LOG_FILE is enabled). (Only the default Logback setting is supported.)
logging.file.name LOG_FILE If defined, it will be used in the default logging configuration.
logging.file.max-size LOG_FILE_MAX_SIZE Maximum log file size (if LOG_FILE is enabled). (Only the default Logback setting is supported.)
logging.file.max-history LOG_FILE_MAX_HISTORY Maximum number of archive log files to keep (if LOG_FILE is enabled). (Only the default Logback setting is supported.)
logging.file.path LOG_PATH If defined, it will be used in the default logging configuration.
logging.file.total-size-cap LOG_FILE_TOTAL_SIZE_CAP The total size of log backups to keep (if LOG_FILE is enabled). (Only the default Logback setting is supported.)
logging.pattern.console CONSOLE_LOG_PATTERN The logging mode used on the console (STDOUT). (Only the default Logback setting is supported.)
logging.pattern.dateformat LOG_DATEFORMAT_PATTERN Additional mode for recording date formats. (Only the default Logback setting is supported.)
logging.pattern.file FILE_LOG_PATTERN Logging mode used in the file (ifLOG_FILEEnabled). (Only the default Logback setting is supported.)
logging.pattern.level LOG_LEVEL_PATTERN Format to use when rendering log levels (default%5p). (Only the default Logback setting is supported.)
logging.pattern.rolling-file-name ROLLING_FILE_NAME_PATTERN Mode of transition log file names (default${LOG_FILE}.%d{yyyy-MM-dd}.%i.gz). (Only the default Logback setting is supported.)
PID PID The current process ID (found if possible and if it has not been defined as an OS environment variable).

All supported logging systems can view system properties when parsing their configuration files

Logback extension

Spring Boot includes a number of Logback extensions to help with advanced configuration. You can use these extensions in the logback-spring.xml configuration file

Because the standard logback.xml configuration file loads too early, you cannot use extensions in it. You need to use logback-spring. XML or define a logging.config attributeCopy the code

<springProfile>

Using the tag, you can choose to include or exclude the configuration section based on the active Spring configuration file

For example,

<springProfile name="test">
    <! -- Configuration enabled when the "test" configuration file is active -->
</springProfile>

<springProfile name="dev | test">
    <! -- Configuration enabled when the "dev" or "test" configuration file is active -->
</springProfile>

<springProfile name=! "" dev">
    <! -- Configuration enabled when the "dev" configuration file is not active -->
</springProfile>
Copy the code

<springProfile> is supported anywhere within the < Configuration > element

<springProperty>

If you want to access the values in the application.properties file from the Logback configuration file, use the <springProperty> tag. This tag works like the standard <property> tag for Logback.

SpringProperty has four properties

  • Name: indicates the variable name
  • Scope: Which environment context to get the attribute from
  • Source: Which attribute to get
  • DefaultValue: what is the defaultValue if no property is retrieved

Use as follows

<springProperty name="fluentHost" scope="context" source="myapp.fluentd.host" defaultValue="localhost"/>
<appender name="FLUENT" class="ch.qos.logback.more.appenders.DataFluentAppender">
    <remoteHost>${fluentHost}</remoteHost>.</appender>
Copy the code

The default Logback configuration for Spring Boot

The source code

These four XML are the default Logback configuration for Spring Boot, which is why Spring Boot prints a wealth of information for us even if we don’t create logback.xml

logback-spring.xml

The official recommendation is to use logback-spring. XML instead of logback.xml. Spring has full control over log initialization, and you can use Spring’s extended support for logback

The XML configuration


      

<! -- scan: enable "hot update" scanPeriod: enable "hot update" scan period: 60 seconds -->
<configuration scan="true" scanPeriod="300 seconds">

    <! -- Add color converter -->
    <conversionRule conversionWord="clr" converterClass="org.springframework.boot.logging.logback.ColorConverter"/>

    <! Source: which attribute to use defaultValue: defaultValue if not found -->
    <springProperty name="env" scope="context" source="spring.profiles.active" defaultValue="env"/>

    <! -- Custom variable used to configure the log output format, which is as close as possible to the spring Boot default output style %date: Date, default format YYYY-MM-DD HHH: MM: SS,SSS default to use the local time zone, defined by % D {YYYY-MM-DD HHH: MM: SS,SSS} %-5level: Log levels with five placeholders, such as "info" and "error" % Thread: log output thread %class: fully qualified name of the log output class, inefficient %method: method name of the log output %line: line number of the log output, inefficient % MSG: Log message content %n: newline -->
    <property name="LOG_PATTERN" value="%date %-5level ${PID:- } --- [%thread] %class.%method/%line : %msg%n"/>

    <! -- Color log format -->
    <property name="LOG_PATTERN_COLOUR"
              value="${env} %date %clr(%-5level) %magenta(${PID:- }) --- [%thread] %cyan(%class.%method/%line) : %msg%n"/>


    <! - log output. Ch. Qos. Logback. Core. The ConsoleAppender: output to the console - >
    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <! -- Configure log output format -->
            <pattern>${LOG_PATTERN_COLOUR}</pattern>
            <! Character set -->
            <charset>UTF-8</charset>
        </encoder>
    </appender>

    <! -- Log output. Ch. Qos. Logback. Core. Rolling. The RollingFileAppender: rolling output to file - >
    <appender name="ROLLING" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <! Active log file names (absolute and relative paths supported) -->
        <file>logs/app1/app1.log</file>
        <! - rolling strategy. Ch. Qos. Logback. Core. Rolling. SizeAndTimeBasedRollingPolicy: according to the size and time rolling -- >
        <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
            <! When to trigger scrolling, how to scroll, and the naming format of the scrolling file %d: date, default format YYYY-MM-DD, custom format %d{YYYY-MM-dd HHH: MM :ss} % I: indicates the sequence number of the log file within a single scrolling period. Zip: compresses the log file into a ZIP. Logs /app1/backup will be stored in a zip package named app1_%d_% I.ZIP --> after the first log request after 0 o 'clock every day.
            <fileNamePattern>logs/app1/backup/app1_%d{yyyy-MM-dd}_%i.zip</fileNamePattern>

            <! Maximum size of a single log file -->
            <maxFileSize>10MB</maxFileSize>

            <! Delete log files from n scroll cycles (at most, keep history of the first n scroll cycles)-->
            <maxHistory>30</maxHistory>
            <! MaxHistory limits the total size of all log files, and deletes them from the oldest log file.
            <totalSizeCap>1GB</totalSizeCap>
        </rollingPolicy>
        <encoder>
            <! -- Log output format -->
            <pattern>${LOG_PATTERN}</pattern>
            <! Character set -->
            <charset>UTF-8</charset>
        </encoder>
    </appender>


    <! -- Use the following configuration for a non-PORD environment -->
    <springProfile name=! "" prod">
        <! -- logger name: package name or class name, level: start log level, additivity: whether to append the appender of the parent class -->
        <logger name="com.wqlm.boot" level="debug" additivity="false">
            <appender-ref ref="STDOUT"/>
            <appender-ref ref="ROLLING"/>
        </logger>
    </springProfile>



    <! -- root logger -->
    <root level="info">
        <! -- STDOUT, ROLLING --
        <appender-ref ref="STDOUT"/>
        <appender-ref ref="ROLLING"/>
    </root>
</configuration>
Copy the code

The relative path example

For simple configuration, use the application.properties configuration file

Name =logs/app1/app.log # Maximum number of days to keep logs # logging.file. Max -history=30 # Maximum size of a single log file # Logging. The file. The Max - size = 10 MB # dao layer to display the SQL logging.level.com.wqlm.boot.user.dao=debug set the debug levelCopy the code

Reference documentation

Spring Boot official documentation