Springboot integrates logs and views them locally

Table of Contents

1. Import dependencies

2.Write configuration

3.Use

4.Verification

5. Print error message


1. Import dependencies

<!-- logback, backward compatible with log4j, also supports SLF4J-->
<dependency>
             <groupId>ch.qos.logback</groupId>
             <artifactId>logback-classic</artifactId>
</dependency>

2. Write configuration

Including configuring color fonts, saving location, etc.

In the log storage path column, I set it to be stored in the log folder on the d drive.

The main file generates .log type, and info and error generate txt files.

<configuration scan="true" scanPeriod="60 seconds" debug="false">
    <!-- Rendering classes that color logs depend on -->
    <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"/>

    <!-- Log storage path -->
    <property name="log.path" value="D:/log"/>
    <!-- Log output format -->
    <property name="log.pattern"
              value="%clr(%d{${yyyy-MM-dd HH:mm:ss.SSS}}){faint} %clr([%X{mdcTraceId},%X{mdcTraceNum}]){magenta} % clr(${LOG_LEVEL_PATTERN:-%5p}) %clr(${PID:- }){magenta} %clr(- & amp;#45; & amp;#45;){faint} %clr([ .20t ]){faint} %clr(%-40.40logger{39}){cyan} : %m%n${LOG_EXCEPTION_CONVERSION_WORD:-%wEx}"/>
    <property name="file.log.pattern"
              value="%d{${yyyy-MM-dd HH:mm:ss.SSS}} [%X{mdcTraceId},%X{mdcTraceNum}] ${LOG_LEVEL_PATTERN:-%5p} ${PID:- } - & amp;#45; & amp;#45; [ .15t] %-40.40logger{39} : %m%n${LOG_EXCEPTION_CONVERSION_WORD:-%wEx}"/>

    <!-- <springProperty scope="context" name="logFileName" source="spring.application.name" defaultValue="currentLog"/>-->
    <!-- Console output -->
    <appender name="console" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>${log.pattern}</pattern>
            <!-- Logging encoding: Set character set here - -->
            <charset>UTF-8</charset>
        </encoder>
    </appender>

    <!-- Global log output -->
    <appender name="file_application" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <file>${log.path}/application</file>
        <rollingPolicy class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy">
            <fileNamePattern>${log.path}/application/application.%i</fileNamePattern>
            <minIndex>1</minIndex>
            <maxIndex>1</maxIndex>
        </rollingPolicy>
        <triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
            <maxFileSize>5MB</maxFileSize>
        </triggeringPolicy>
        <encoder>
            <pattern>${file.log.pattern}</pattern>
            <!-- Logging encoding: Set character set here - -->
            <charset>UTF-8</charset>
        </encoder>
    </appender>
    <!-- System log output -->
    <appender name="file_info" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <file>${log.path}/info.txt</file>
        <!-- Cycle policy: create log files based on time -->
        <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
            <!-- Log file name format -->
            <fileNamePattern>${log.path}/info/%d{yyyy-MM-dd}-%i.txt</fileNamePattern>
            <!--Maximum value for each file -->
            <maxFileSize>10MB</maxFileSize>
            <!-- Save logs for up to 30 days -->
            <maxHistory>15</maxHistory>
            <!-- Maximum limit -->
            <totalSizeCap>20GB</totalSizeCap>
        </rollingPolicy>
        <encoder>
            <pattern>${file.log.pattern}</pattern>
            <!-- Logging encoding: Set character set here - -->
            <charset>UTF-8</charset>
        </encoder>
        <filter class="ch.qos.logback.classic.filter.LevelFilter">
            <!-- Level of filtering -->
            <level>INFO</level>
            <!-- Operation when matching: receive (record) -->
            <onMatch>ACCEPT</onMatch>
            <!-- Action when there is no match: reject (do not log) -->
            <onMismatch>DENY</onMismatch>
        </filter>
    </appender>

    <appender name="file_error" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <file>${log.path}/error.txt</file>
        <!-- Cycle policy: create log files based on time -->
        <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
            <!-- Log file name format -->
            <fileNamePattern>${log.path}/error/%d{yyyy-MM-dd}-%i.txt</fileNamePattern>
            <!--Maximum value for each file -->
            <maxFileSize>10MB</maxFileSize>
            <!-- Save logs for up to 30 days -->
            <maxHistory>15</maxHistory>
            <!-- Maximum limit -->
            <totalSizeCap>20GB</totalSizeCap>
        </rollingPolicy>
        <encoder>
            <pattern>${file.log.pattern}</pattern>
            <!-- Logging encoding: Set character set here - -->
            <charset>UTF-8</charset>
        </encoder>
        <filter class="ch.qos.logback.classic.filter.LevelFilter">
            <!-- Level of filtering -->
            <level>ERROR</level>
            <!-- Operation when matching: receive (record) -->
            <onMatch>ACCEPT</onMatch>
            <!-- Action when there is no match: reject (do not record) -->
            <onMismatch>DENY</onMismatch>
        </filter>
    </appender>

    <!-- System module log level control -->
    <logger name="com.org.sys" level="debug"/>
    <!-- Spring log level control -->
    <logger name="org.springframework" level="warn"/>
    <logger name="com.zaxxer.hikari" level="warn"/>
    <logger name="io.lettuce.core" level="warn"/>
    <logger name="io.seata.core" level="warn"/>
    <logger name="com.netflix.loadbalancer" level="warn"/>

    <root level="info">
        <appender-ref ref="console"/>
    </root>

    <!--System operation log-->
    <root level="info">
        <appender-ref ref="file_application"/>
        <appender-ref ref="file_info"/>
        <appender-ref ref="file_error"/>
    </root>
</configuration>

3.Use

Two methods 1. Add annotations to the class 2. Create through LoggerFactory

It should be noted that the method of adding @Slf4j annotation to the class requires dependence on lombok, so the lombok dependency must be imported.

 <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
</dependency>
@RestController
@RequestMapping("/test")
@CrossOrigin
@Slf4j
public class TestController {
 
    //Edit the xml configuration file. The controller layer indicates the use of printing and display through logger.info.
    private static final Logger logger = LoggerFactory.getLogger(TestController.class);


    @RepeatSubmit
    @PostMapping("/test")
    public String login() {
        User user = new User();
        user.setName("Logger");
        log.info("Test the use of the annotation @Slf4j,{}",JSON.toJSONString(user));
        logger.info("Print log information{}", JSON.toJSONString(user));
        return "Hello, doPost method";
    }
}

4.Verification

postman interface test

The log printed by the console

Logs saved in local log folder

5.Print error message

Use: log.error() or logger.error()

 public String login() {
        User user = new User();
        user.setName("Logger");
        log.info("Test the use of the annotation @Slf4j,{}",JSON.toJSONString(user));
        logger.info("Print log information{}", JSON.toJSONString(user));
        log.error("error message");
        logger.error("error message");
        return "Hello, doPost method";
    }

Console printing

At this time, go to err.txt or application.log in the log folder.

error.txt

application.log

Difference: In general, err and info of application are stored according to classification.

The knowledge points of the article match the official knowledge files, and you can further learn related knowledge. Java Skill TreeHomepageOverview 138569 people are learning the system