SpringBoot default log configuration output level

Springboot default configuration

Let's demonstrate it in the test class

package com.staticzz.springboot_logging;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringbootLoggingApplicationTests {


    /**
     * SLF4J Loggers
     */
    Logger logger = LoggerFactory.getLogger(getClass());

    @Test
    public void contextLoads() {

        /**
         * Log level, from low to high
         * We can adjust the log level, and the log will only take effect after this level
         */
        logger.trace("This is trace journal");
        logger.debug("This is debug information");
        logger.info("This is info information");
        /**
         * After running, the output starts from info information, indicating that Springboot defaults to info level log information
         */
        logger.warn("This is warning information");
        logger.error("This is error information");
    }
}

Dynamic presentation:

If we need to modify the default log level, how can we modify it?

It can be written in the configuration file of SpringBoot

logging.level.com.staticzz=trace

This code means that I will com The log level of all classes under the staticzz package is set to the trace level

Dynamic presentation:

Then we can go to application Specify logging. In the properties configuration file Level, can you specify other parameters?

The answer is yes

#Specify the log level under a package
logging.level.com.staticzz=trace
#Specify the log file name
#logging.file=SpringBoot.log
#Specify the log output path. If it is not specified, it will be output to the console by default
logging.path=C:/Users/socra
#Specify console output format
#logging.pattern.console=
#Specifies the file output format
logging.pattern.file=%d{-yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-51level %logger{50} - %msg%n

There is a problem to pay attention to here, logging File and logging Path cannot be used at the same time, and there will be conflicts. We only need to choose one of two configurations!

demonstration:

Then why is the default level of springboot log info? Where is this level specified by springboot? What is the default configuration of its log? What is configured in the default configuration?

We all know that SpringBoot uses SLF4J+logback to record logs. Next, we find the logback jar package in the dependent spingboot package to see what is configured by default?

Just mentioned that the default log level in SpringBoot is INFO level. We can see from the above demonstration that the log configuration in SpringBoot mainly uses the following files. Here I list them one by one:

  • base.xml

  • defaults.xml

  • console-appender.xml

  • file-appender.xml

  • LoggingSystemProperties

Here I list all the contents of these documents and explain their functions!

base.xml

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

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

<included>
    <!--The default configuration is introduced xml file-->
   <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}"/>
    
    <!--Introduction of console output format xml file-->
    <include resource="org/springframework/boot/logging/logback/console-appender.xml" />
    
    <!--The of file output format is introduced xml file-->
    <include resource="org/springframework/boot/logging/logback/file-appender.xml" />
   
    <!-- Here it is Springboot Log default level configuration-->
    <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" />
    
    <!--Controls the format of the default output->
   <property name="CONSOLE_LOG_PATTERN" value="${CONSOLE_LOG_PATTERN:-%clr(%d{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}}"/>
    
    <!--File default output format->
  <property name="FILE_LOG_PATTERN" value="${FILE_LOG_PATTERN:-%d{yyyy-MM-dd HH:mm:ss.SSS} ${LOG_LEVEL_PATTERN:-%5p} ${PID:- } --- [%t] %-40.40logger{39} : %m%n${LOG_EXCEPTION_CONVERSION_WORD:-%wEx}}"/>

   <appender name="DEBUG_LEVEL_REMAPPER" class="org.springframework.boot.logging.logback.LevelRemappingAppender">
      <destinationLogger>org.springframework.boot</destinationLogger>
   </appender>
   <!--Default specified level->
   <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.crsh.plugin" level="WARN"/>
   <logger name="org.crsh.ssh" level="WARN"/>
   <logger name="org.eclipse.jetty.util.component.AbstractLifeCycle" level="ERROR"/>
   <logger name="org.hibernate.validator.internal.util.Version" level="WARN"/>
   <logger name="org.springframework.boot.actuate.autoconfigure.CrshAutoConfiguration" level="WARN"/>
   <logger name="org.springframework.boot.actuate.endpoint.jmx" additivity="false">
      <appender-ref ref="DEBUG_LEVEL_REMAPPER"/>
   </logger>
   <logger name="org.thymeleaf" additivity="false">
      <appender-ref ref="DEBUG_LEVEL_REMAPPER"/>
   </logger>
</included>

So here's a problem?

defaults. The default console in the XML file and the output format of the default file refer to relevant environment variables in the code. Where are these environment variables? We also modified these configurations in Springboot,

${CONSOLE_LOG_PATTERN:-%clr(%d{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}}"/>

Answer: in the following class

LoggingSystemProperties.java

/*
 * Copyright 2012-2016 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.boot.logging;

import org.springframework.boot.ApplicationPid;
import org.springframework.boot.bind.RelaxedPropertyResolver;
import org.springframework.core.env.Environment;

/**
 * Utility to set system properties that can later be used by log configuration files.
 *
 * @author Andy Wilkinson
 * @author Phillip Webb
 */
class LoggingSystemProperties {

   static final String PID_KEY = LoggingApplicationListener.PID_KEY;

   static final String EXCEPTION_CONVERSION_WORD =          LoggingApplicationListener.EXCEPTION_CONVERSION_WORD;

   static final String CONSOLE_LOG_PATTERN = LoggingApplicationListener.CONSOLE_LOG_PATTERN;

   static final String FILE_LOG_PATTERN = LoggingApplicationListener.FILE_LOG_PATTERN;

   static final String LOG_LEVEL_PATTERN = LoggingApplicationListener.LOG_LEVEL_PATTERN;

   private final Environment environment;

   LoggingSystemProperties(Environment environment) {
      this.environment = environment;
   }

   public void apply() {
      apply(null);
   }

   public void apply(LogFile logFile) {
      RelaxedPropertyResolver propertyResolver = RelaxedPropertyResolver
            .ignoringUnresolvableNestedPlaceholders(this.environment, "logging.");
      setSystemProperty(propertyResolver, EXCEPTION_CONVERSION_WORD,
            "exception-conversion-word");
      setSystemProperty(PID_KEY, new ApplicationPid().toString());
      setSystemProperty(propertyResolver, CONSOLE_LOG_PATTERN, "pattern.console");
      setSystemProperty(propertyResolver, FILE_LOG_PATTERN, "pattern.file");
      setSystemProperty(propertyResolver, LOG_LEVEL_PATTERN, "pattern.level");
      if (logFile != null) {
         logFile.applyToSystemProperties();
      }
   }

   private void setSystemProperty(RelaxedPropertyResolver propertyResolver,
         String systemPropertyName, String propertyName) {
      setSystemProperty(systemPropertyName, propertyResolver.getProperty(propertyName));
   }

   private void setSystemProperty(String name, String value) {
      if (System.getProperty(name) == null && value != null) {
         System.setProperty(name, value);
      }
   }

}

About the format of console output 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>
         <charset>utf8</charset>
      </encoder>
   </appender>
</included>

About the format of log file output 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.FixedWindowRollingPolicy">
         <fileNamePattern>${LOG_FILE}.%i</fileNamePattern>
      </rollingPolicy>
      <triggeringPolicy
         class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
         <MaxFileSize>10MB</MaxFileSize>
      </triggeringPolicy>
   </appender>
</included>

We have seen the default configuration file of SpringBoot log. What if we customize the log configuration file?

The method is:

Put the configuration file of each log framework under the class path

Logback spring is officially recommended XML this format

When we use

logback.xml, the log framework loads the configuration file directly, so the advanced functions cannot be used

logback-Spring. When the configuration file is loaded by SpringBoot, you can use advanced functions such as Spring. XML Profile, which we have used before, is Spring's underlying multi environment support, so we can specify that the configuration file of a log will only take effect in a certain environment

<springProfile name="profile attribute">
 <!-- configuration to be enabled when the "staging" profile is active -->
    A configuration of the specified log takes effect only in the set environment
</springProfile>

Keywords: Java Spring Spring Boot

Added by mitchell on Sun, 02 Jan 2022 05:01:13 +0200