Spring Boot Log Log Use Tutorial

Posted by arbitter on Wed, 10 Jul 2019 18:57:36 +0200

If we write any Spring Boot program, we probably can't get around the log log framework (component).
Logs are used to locate problems in the eyes of most programmers.This is important.

Source Download for this project Note that the source code provided by this project has been rewritten at a later stage and that some date descriptions are inconsistent.

If you just want to know how the Spring boot log works, watch 3.2 directly using the Spring Boot Logback

1 Log Log Overview

1.1 What can the Log Log component do?

Log can do a lot of things, for learning programs, testing engineers, log can locate problems, solve problems, is the biggest function point.

  1. Logging everything helps us keep track of what the program does, whether it is a normal input or output or an exception.
  2. Locating problem logs can help programmers debug problems and help testers locate problems
  3. Record Analysis User Behavior Statistical Analysts record a user's collective behavior to analyze user habits and business values
  4. Backup and restore real-time data database engineers use it as a special database

Level Log Level for 1.2 Logs

The log level is a prioritization of logging information.Usually from light to heavy:

  1. TRACE
  2. DEBUG
  3. INFO
  4. WARN
  5. ERROR

Normally when we specify the log level to be INFO, the TRACE DEBUG level log will not be printed out, similarly if ERROR is specified, other types of logs will not be printed.

1.3 Log Output Log Import

Normally logs are stored on disk as text streams, or in relational databases or No Sql

  1. text
  2. Relational Database
  3. No Sql
  4. Console Console Console

Normal log components can customize the output format.

1.4 Spring Boot Log Component Log Plugin

Of course, it's okay to develop your own log components, but it's not really difficult. In some special scenarios, many companies use their own log components, but for most applications, we can solve our problem by using standard log components.

The most common Spring Boot log components include

  1. Default configuration for Logback Spring Boot Convention
  2. log4j
  3. log4j2
  4. slf4j
  5. JUL

For most scenarios, we recommend the log logback that comes with Spring Boot.

Many bad media grab articles without indicating the source. I am a fishpro program fish, the author of this article.

2 Spring Boot Logback

3.1 About Logback

In Spring Boot, logback is based on slf4j.

The full name of slf4j is Simple Loging Facade For Java, which is just a unified interface for providing log output to Java programs. It is not a specific log implementation. It can implement most of the log components.

As shown in the figure above, logback uses slf4j, logback-classic.jar, and logback-core.jar to implement logback logging.

3.2 Generate a Spring Boot project for testing

Creating a project using IDEA is actually created from (https://start.spring.io/), but it is more convenient. We usually create a Spring Boot project from IDEA.

Note that the IDEA creation process for mac and windows is the same.

1) File>New>Project, select Spring Initializr as shown below and click Next to proceed

2) Fill in GroupId (package name), Artifact (project name).Click Next

  • groupId=com.fishpro
  • artifactId=log

3) Choose to rely on Spring Web Starter for front hooking

4) Project name set to spring-boot-study-log

5) Write a simple example to show how easy it is to use the log component

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class LogApplication {

    public static void main(String[] args) {
        Logger logger =LoggerFactory.getLogger(LogApplication.class);
        SpringApplication.run(LogApplication.class, args);
        logger.debug("This is a debug message");//Note that the spring default log output level is info, so this sentence will not be printed to the console by default
        logger.info("This is an info message");
        logger.warn("This is a warn message");
        logger.error("This is an error message");
    }

}

Run to see the output hello world

2019-07-10 23:51:49.225  INFO 3906 --- [           main] com.fishpro.log.LogApplication           : Started LogApplication in 1.688 seconds (JVM running for 2.317)
2019-07-10 23:51:49.226  INFO 3906 --- [           main] com.fishpro.log.LogApplication           : This is an info message
2019-07-10 23:51:49.227  WARN 3906 --- [           main] com.fishpro.log.LogApplication           : This is a warn message
2019-07-10 23:51:49.227 ERROR 3906 --- [           main] com.fishpro.log.LogApplication           : This is an error message

3.3 Dependency Configuration Pom.xml

You can see that many people on the Internet have posted logback dependency configurations. In fact, you can see from the dependency packages that by default logback dependencies do not need to be configured separately.No separate configuration is required, no separate configuration is required, and no separate configuration is required.

3.4 Configuring logback using YML

3.4.1 Write a Controller layer class as the IndexController for testing

@Controller
public class IndexController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    @RequestMapping("/")
    String index(){
        logger.debug("This is a debug message");
        logger.info("This is an info message");
        logger.warn("This is a warn message");
        logger.error("This is an error message");
        return "index";
    }
}

Execute http://locahost:8081/

As shown above, we do not have a log for DEBUG, that is, logger.debug("This is a debug message"); it is not output to the console.

In fact, Spring Boot is a convention larger than configuration, that is, it has a configuration file called base.xml, in which the log level of output is already configured by default. Let's look at base.xml, as shown in the XML code below, root level="INFO" already defines the log output levelNot INFO.That's why I see the console doesn't output the DEBUG log.

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

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

<included>
  <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}"/>
  <include resource="org/springframework/boot/logging/logback/console-appender.xml" />
  <include resource="org/springframework/boot/logging/logback/file-appender.xml" />
  <root level="INFO">
    <appender-ref ref="CONSOLE" />
    <appender-ref ref="FILE" />
  </root>
</included>

3.4.2 Configured in application.yml

Set the level of level level level to DEBUG as follows

logging:
  level:
    com.fishpro.log: debug

Execute http://locahost:8081/Output in the browser The following log shows that there is already a DEBUG log

2019-07-08 12:51:30.423  INFO 36966 --- [nio-8081-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring DispatcherServlet 'dispatcherServlet'
2019-07-08 12:51:30.423  INFO 36966 --- [nio-8081-exec-1] o.s.web.servlet.DispatcherServlet        : Initializing Servlet 'dispatcherServlet'
2019-07-08 12:51:30.428  INFO 36966 --- [nio-8081-exec-1] o.s.web.servlet.DispatcherServlet        : Completed initialization in 5 ms
2019-07-08 12:51:30.447 DEBUG 36966 --- [nio-8081-exec-1] c.f.s.controller.IndexController         : This is a debug message
2019-07-08 12:51:30.447  INFO 36966 --- [nio-8081-exec-1] c.f.s.controller.IndexController         : This is an info message
2019-07-08 12:51:30.448  WARN 36966 --- [nio-8081-exec-1] c.f.s.controller.IndexController         : This is a warn message
2019-07-08 12:51:30.448 ERROR 36966 --- [nio-8081-exec-1] c.f.s.controller.IndexController         : This is an error message

3.4.3 Detailed configuration in application.yml

The following configuration code specifies the output level of the log, the path to the log storage, and the format of the output.

logging:
  #level Log level Specifies Log Output for Namespace
  level:
    com.fishpro.log: debug
  #File specifies the storage path of the output file
  file: logs/app.log
  #Patterns specify the log output format for the output scene
  pattern:
    console: "%d %-5level %logger : %msg%n"
    file: "%d %-5level [%thread] %logger : %msg%n"

Execute http://locahost:8081/

00:08:15 [reactor-http-nio-2] DEBUG com.fishpro.log.LogApplication - This is a debug message
00:08:15 [reactor-http-nio-2] INFO  com.fishpro.log.LogApplication - This is an info message
00:08:15 [reactor-http-nio-2] WARN  com.fishpro.log.LogApplication - This is a warn message
00:08:15 [reactor-http-nio-2] ERROR com.fishpro.log.LogApplication - This is an error message

At the same time, we can see the multiprocessing logs folder under the project root path, with the app.log file below, which also records the output of the log.

3.4.4 Configuration in different environments

We can configure different log configuration items in the environment of dev, prod, test, etc. We just need to set them according to our configuration file.

Refer to how to configure different environments in Spring Boot to separate dev elopment, test, and prod environments Multiple Environment Configuration in Spring Boot

3.5 Use logback-spring.xml to configure logback logs

If you need a more detailed custom logback log, you need to configure it using an xml configuration file.

Using logback-spring.xml to customize the configuration of logs mainly requires understanding the detailed logback-spring.xml feature points and what can be configured.

3.5.1 Specify logback-spring.xml path

First we need to know where the logback-spring.xml file is located.

The default logback-spring.xml path is in the resource folder, which means you only need to create a new file, logback-spring.xml, in the resource folder.

3.5.2 Custom configuration using logback-spring.xml

Here we use a custom configuration implementation

  1. Output the log to the specified directory and store it daily in the format of date yyyy-MM-dd. Note that if not specified, the directory applog here refers to the root directory of the project (if your project is a multi-module configuration, not a module directory)
  2. Configure xml
<?xml version="1.0" encoding="UTF-8"?>
<configuration scan="true" scanPeriod="60 seconds" debug="false">
   <contextName>logback</contextName>
   <!--Output to console-->
   <appender name="console" class="ch.qos.logback.core.ConsoleAppender">
       <encoder>
           <!--Format output:%d Indicates the date,%thread Represents the thread name,%-5level: Level shows 5 character width from left%msg: Log messages,%n Is a line break-->
           <pattern>%d{HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n</pattern>
           <charset>UTF-8</charset>
       </encoder>
   </appender>

   <!--Generate log by day-->
   <appender name="logFile" class="ch.qos.logback.core.rolling.RollingFileAppender">
       <Prudent>true</Prudent>
       <!-- Filter, print only ERROR Level Log -->
       <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
           <!--File name of log file output-->
           <FileNamePattern>
               applog/%d{yyyy-MM-dd}/%d{yyyy-MM-dd}.log
           </FileNamePattern>
           <!--Days of log file retention-->
           <MaxHistory>15</MaxHistory>
       </rollingPolicy>
       <layout class="ch.qos.logback.classic.PatternLayout">
           <Pattern>
               %d{yyyy-MM-dd HH:mm:ss} -%msg%n
           </Pattern>
       </layout>
   </appender>

   <logger name="com.fishpro.log" additivity="false">
       <appender-ref ref="console"/>
       <appender-ref ref="logFile"/>
   </logger>
   
   <!-- Set up Spring&Hibernate Log Output Level -->
   <logger name="org.springframework" level="WARN"/>
   <logger name="org.mybatis" level="WARN"/> 
   <logger name="com.ibatis" level="DEBUG"/> 
   <logger name="com.ibatis.common.jdbc.SimpleDataSource" level="DEBUG"/> 
   <logger name="com.ibatis.common.jdbc.ScriptRunner" level="DEBUG"/> 
   <logger name="com.ibatis.sqlmap.engine.impl.SqlMapClientDelegate" level="DEBUG"/>


      
   <logger name="java.sql.Connection" level="DEBUG"/>  
   <logger name="java.sql.Statement" level="DEBUG"/> 
   <logger name="java.sql.PreparedStatement" level="DEBUG"/> 
   <logger name="com.ruidou.baoqian.mapper" level="DEBUG"/>

   <!-- Log Configuration in Development Environment -->
   <root level="error">
       <appender-ref ref="console"/>
       <appender-ref ref="logFile"/>
   </root>
</configuration>

Execute http://locahost:8081/

At this point, you will find that there are more applog folders in the project root directory, and it is important that the applog/2019-07-08/2019-07-08.log records files by date.

priority

Interestingly, when we configured the XML file with application.yml, he executed logback-spring.Configuration in xml, all logback-spring.xml configurations take precedence

4 How multi-log components unify the framework

Sometimes a system uses multiple log frameworks in its Application, such as how can Logback and log4j be unified?

Summary: This chapter describes the simple use of the log component Spring Boot Logback. In the next section, we will detail the label meaning of logback-spring.xml and the attribute meaning of the label.

Topics: PHP Spring xml Java SQL