Make writing a habit together! This is the 12th day of my participation in the “Gold Digging Day New Plan · April More text Challenge”. Click here for more details.

The introduction

SpringBoot provides the default configuration file base.xml for Logback, which defines the default journal output level as INFO.

    ERROR(40."ERROR"),
    WARN(30."WARN"),
    INFO(20."INFO"),
    DEBUG(10."DEBUG"),
    TRACE(0."TRACE");
Copy the code

I Logback usage

Slf4J, or Simple Logging Facade for Java, is not a specific Logging solution and only serves a wide variety of Logging systems. Slf4J is a simple Facade for logging systems that allows end users to use the logging systems they want when deploying their applications.

SLF4J is more like repackaging these logging frameworks, providing a common interface for users to call, no matter how the underlying framework changes, just replacing the dependencies, rather than changing to see where the project called the original logging system’s methods.

Logback is a built-in logging framework for SpringBoot. Spring-boot-starter includes spring-boot-starter-logging, which is the default logging framework for SpringBoot. Official document: logback.qos. Ch /manual/

1.1 Facade mode

Slf4j is a typical application of facade pattern, whose core isExternal communication with a subsystem must be done through a unified facade object, making the subsystem easier to use.

The slf4J usage is the perennial “Logger Logger = loggerFactory.getLogger (object.class);” Slf4j provides a Logger interface by LoggerFactory.

We can use MVN to introduce Lombok and annotations to make it easier to use SLF4J.

  1. POJO getter/setter/toString; Exception handling; The shutdown of I/O streams and so on, boilerplate code that was both untechnical and ugly, Lombok was born.

  2. The last release of IDEA 2020 has Lombok built in, and SpringBoot versions after 2.1.x have Lombok dependencies built into the Starter

1.2 Application examples of SLF4J

package com.example.demo;

import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.test.context.SpringBootTest;

// new spring-boot-starter-test no longer integrates junit, but junit-Jupiter, no longer uses @runwith () annotation.
//@RunWIth(SpringRunner.class)
@SpringBootTest
public class LoggerTest {
private final Logger logger = LoggerFactory.getLogger(LoggerTest.class);

@Test
    public void test1(a) {

    logger.debug("debug...");

    logger.info("info..."); // The system's default diary level
    logger.error("error..."); }}Copy the code

1.3 application. The properties

The priority of the configuration file varies according to the directory where the configuration file resides, as shown in Figure 1-4

  1. Config in the current project root directory
  2. Current project root directory
  3. In the config directory of the resource directory
  4. The resource directory
  5. When using spring.config.location to specify an external configuration file, this configuration file must fully meet the requirements of the current project runtime, because it does not merge configuration files in the Resources directory.

Properties and application.yml have the same effect. If both application.properties and application.yml files exist in the Spring Boot project, both files are valid. However, application.properties takes precedence over application.yml.

Use either Application.properties or application.yml, don’t confuse yourself with both

Unlike the disordered properties file, YAML has an orderly configuration.

The spring.config.name environment variable can be set to specify the configuration file name.

1.4 Enabling the Debug mode

A: Set debug=true in application.properties. When this property is set to true, the core Loggers (including embedded containers, Hibernate, and Spring) will output more content, but your own application logs will not output debug.

Method 2: Enable it in compilation Settings

By default, Spring Boot prints logs to the console, not to log files. Properties or application.yml can be configured, but only for simple scenarios, such as save path and log format, etc., and for complex scenarios, such as logs that distinguish info from error and generate a log file every day, etc., you can only customize the configuration.

1.5 Customizing the LogBack Configuration file

Groovy: Logback: logback-spring. XML, logback-spring.groovy, logback. XML, Logback

Properties, log4j-spring. XML, log4j.properties, log4j.xml

Log4j2: Log4j2 – spring XML, Log4j2. XML

JDK (Java Util Logging) : logging.properties


      
<configuration>
    <property name = "ENCODER_PATTERN" value = "%d{MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{80} - %msg%n"/>
    <! -- Console log: Print all logs to console -->
    <appender name="console" class="ch.qos.logback.core.ConsoleAppender">
        <! -- Control the output stream object, default system. out to system. err-->
        <target>System.err</target>
        <! -- Log message format configuration -->
        <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
            <pattern>${ENCODER_PATTERN}</pattern>
        </encoder>
    </appender>
    <! -- Root Logger configuration -->
    <root level="info">
        <appender-ref ref="console"/>
    </root>
</configuration>
Copy the code

FileInfoLog and fileErrorLog

    <appender name="fileInfoLog" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <filter class="ch.qos.logback.classic.filter.LevelFilter">
            <level>ERROR</level>
            <onMatch>DENY</onMatch>
            <onMismatch>ACCEPT</onMismatch>
        </filter>
        <encoder>
            <pattern>
                %msg%n
            </pattern>
        </encoder>
        <! -- Scroll strategy -->
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <! -- -- -- > path
            <fileNamePattern>/Users/mac/Desktop/log/tomcat/test/info.%d.log</fileNamePattern>
        </rollingPolicy>
    </appender>


    <appender name="fileErrorLog" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <filter class="ch.qos.logback.classic.filter.ThresholdFilter">
            <level>ERROR</level>
        </filter>
        <encoder>
            <pattern>
                %msg%n
            </pattern>
        </encoder>
        <! -- Scroll strategy -->
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <! -- -- -- > path
            <fileNamePattern>/Users/mac/Desktop/log/tomcat/test/error.%d.log</fileNamePattern>
        </rollingPolicy>
    </appender>


    <! -- Root Logger configuration -->
    <root level="info">
        <appender-ref ref="fileInfoLog"/>
        <appender-ref ref="fileErrorLog"/>

    </root>
Copy the code

To view the log file being changed: tail -f error.2022-04-09.log

II Use of SpringBoot built-in plug-ins (Jackson and Lombok)

Idea2021.2.2 comes bundled with the Jackson and Lombok plug-ins

2.1 lombok

Lombok automatically generates constructors, getters/setters, equals, hashcode, and toString methods for properties at compile time via annotations.

Projectlombok.org/features/al…

  1. If you do not specify a version number for maven, the latest version 1.18.22 will not be found.
<dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.22</version>
        </dependency>

Copy the code

If you don’t want to write private final Logger every time loggerFactory.getLogger (current class name.class); You can use the @slf4j annotation

@Slf4j
    public void test1(a) {

    log.debug("debug...");

    log.info("info..."); // The system's default diary level
    log.error("error...");



}
Copy the code

The @data annotation, applied to a class, automatically generates setter/getter, equals, hasCode, and toString methods for all attributes of the class.

@Builder features chain assignment when creating objects.

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class Student {

Copy the code

2.2 jackson

SpringBoot has Jackson built in to serialize and deserialize JSON.

Jackson uses ObjectMapper classes to serialize POJO objects into JSON strings, and can also deserialize JSON strings into POJO objects.

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

        String str = mapper.writeValueAsString(stu);
        Student stu = mapper.readValue(str,Student.class);

Copy the code

Jackson includes many annotations to personalize the serialization and deserialization operations.

  1. @JsonProperty(alias)Action on an attribute to specify an alias for the attribute.
  2. @JsonIgnoreApplies to a property, using this annotation to ignore the property.
  3. @JsonIgnoreProperties({propertyName1,propertyName2}), applied to a class, to omit a set of attributes.
  4. @ JsonFormat (pattern = "").Used to format dates.

For example, @jsonformat (pattern = “YYYY-MM-DD HH: MM :ss”) formats the time as year-month-day hour: minute: second.

    @JsonIgnore
    private String gender;

    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    @JsonProperty("bd")
    private Date birthday;

Copy the code

see also

The shell script completes the extraction of the log file

Idea, quick search shortcut key: command+ O