Hot deployment and logging of SpringBoot

Posted by jimmyhumbled on Mon, 07 Feb 2022 04:03:53 +0100

1. Hot deployment of devtools in SpringBoot

1.1. What is hot deployment

Hot deployment means that every time we modify some codes and related configurations during development, we don't need to restart the whole system. We just need to wait a few seconds to automatically load the modified things successfully.

1.2. How to enable SpringBoot hot deployment

1. Introduce devtools dependency

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-devtools</artifactId>
    <optional>true</optional>
</dependency>

2. Check setting, as shown in the red box below

3. Press and hold ctrl + shift + alt + / to display the interface as shown in the figure below. Select 1, registry

4. After the figure below appears, check the configuration of the red box in the picture

2. Introduction to SpringBoot log

2.1 facade

Now there are two main facades in the market, one is JCL and the other is slf4j. Spring defaults to JCL, but slf4j is more powerful than JCL.
slf4j has two main points
Bridge: when each log system needs to be used, there must be an intermediary, called bridge.
Adapter: the adapter is used to convert the existing log framework in our system into slf4j.

2. Appearance log

2.2.1 appearance log of log4j

1. Introduce dependency

<!-- log4j Log core dependency -->
<dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>1.2.14</version>
</dependency>

<!-- slf4j Core dependency of -->
<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-api</artifactId>
    <version>1.7.31</version>
</dependency>

<!-- add to slf4j  log4j Bridge for -->
<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-log4j12</artifactId>
    <version>1.7.31</version>
</dependency>

2. Introduce log4j Properties configuration file

log4j.rootLogger=trance, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m%n

3. Test class, pay attention to the introduced package

package cool.ale;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class Log4jMain {
    public static void main(String[] args) {
        Logger logger = LoggerFactory.getLogger(Log4jMain.class);
        logger.info("log4j journal");
    }
}

2.2.2 appearance log of jul

1. Introducing pom dependency

<!-- introduce JCL Facade dependence -->
<dependency>
    <groupId>commons-logging</groupId>
    <artifactId>commons-logging</artifactId>
    <version>1.2</version>
</dependency>

2. Test class, pay attention to the introduced package

package cool.ale;


import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;


public class JulMain {

    public static void main(String[] args) {
        Log log = LogFactory.getLog(JulMain.class);
        log.info("JCL journal");


    }
}

3. If it is run directly, the log we print is still log4j, because the JCL dynamic search mechanism instantiates the log in the order of Commons logging Properties - > system environment variables - > log4j - > Jul - > simplelog - > nooplog. At this time, we can specify a JCL configuration file, commons logging Properties, as follows:

org.apache.commons.logging.Log = org.apache.commons.logging.impl.Jdk14Logger

2.3. Unified log

When there are two or more logs in our system, we can unify the log implementation and introduce the following jar package.

<!-- In order to unify the log implementation, the JCL Convert to SLF4J
 add to JCL-SLF4J Adapter for
 -->
<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>jcl-over-slf4j</artifactId>
    <version>1.7.30</version>
</dependency>

3. SpringBoot log integration

3.1. SpringBoot default log integration

The bottom layer of SpringBoot uses slf4j+logback for logging.

3.2. SpringBoot log usage

log level

TRACE,DEBUG,INFO,WARN,ERROR,FATAL or OFF.

First, we need to define a logger. Note that slf4j package must be introduced and tested in the startup class of SpringBoot. The test code is as follows:

package cool.ale;

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

@SpringBootApplication
public class Application {

    // Declare a logger
    static Logger logger = LoggerFactory.getLogger(Application.class);

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);

        logger.trace("track");
        logger.debug("debugging");
        logger.info("information");
        logger.warn("warning");
        logger.error("abnormal");
    }

}

After running, we find that the default level of log is INFO by looking at the console, as shown below:

We can do it in application Modify the configuration in the YML file. As shown below, modify the log level of a package. Com Ale package:

3.3. SpringBoot log format

3.3.1 introduction to log format

For example, take the above illustration as an example:

journalFormat description
2021-07-09 14:30:09.136Date and time, millisecond precision, easy to sort
TRACE,DEBUG,INFO,WARN,ERROR,FATAL or OFF.log level
5104Process ID
- - -Static format configured in log configuration file
[ main]The name of the thread. Main stands for the main thread
cool.ale.ApplicationClass name of logging
trackThe information we output

3.3.2 format of modification date

We can do it in application The yml file is modified according to the configuration. When our yml configuration file has% and other parameters, it needs to be enclosed in single quotation marks.

logging:
  pattern:
    console: '%d{yyyy/MM/dd-HH:mm:ss}'

3.3.3 detailed description of parameters

According to the above log format, we will talk about several parameters:

1. Parameter% CLR of output date (% d {${log_dateformat_pattern: - yyyy MM DD)
HH:mm:ss.SSS}}){faint}
1.1 first%clr {faint} represents the color of this log output, {faint} represents no color.

1.2,(%d{${LOG_DATEFORMAT_PATTERN:-yyyy-mm-dd
HH:mm:ss.SSS}): the contents to be output are represented in parentheses. First look for log in our system environment variable_ DATEFORMAT_ The pattern parameter, if not found, is yyyy mm DD
HH:mm:ss.SSS outputs system time, but LOG_DATEFORMAT_PATTERN can also be used in application Configure in YML as follows:

logging:
  pattern:
    dateformat: -yyyy-MM-dd

1.3.% d {${- yyyy MM DD HH: mm: SS. SSS}}:% d is a date output format of logback, - yyyy MM DD HH: mm: SS SSS is the real format.

2,%clr({${LOG_LEVEL_PATTERN:-%5p}})
2.1. Output each log level, such as TRACE,DEBUG,INFO,WARN,ERROR,FATAL or OFF. There is no need to set the color specially. Each log level will have a default color.
2.2. -% 5 indicates right alignment, with a total of 5 characters.
2.3. p represents the level of output log.

3,%clr({${PID:–%5p}}){magenta}
3.1. {${PID: –% 5p}}: get the process ID from the system.

3.4. SpringBoot log output to file

There are two ways for SpringBoot to output logs by file, which can be found in application The configuration in the YML configuration file is as follows:

logging:
  file:
    #name: log.log
    path: D:/

1,logging.file.name can specify a file name or a physical path. If the file name is specified directly, the log will be generated under the relative path of the project.
2,logging.file.path cannot specify a file name, but a physical path needs to be specified. The default log name is: spring log.

3.5. SpringBoot log archiving

1,logging. logback. rollingpolicy. File name pattern configuration
The default format is as follows:
${LOG_FILE}.%d{yyyy-MM-dd}.%i.gz
${LOG_FILE} corresponds to logging file. name
%d{yyyy-MM-dd} year month day
%i index, which increments the file index when the file exceeds the specified size

When we set the following configuration:

logging:
  file:
    name: D:/logs/log.log
    max-size: 5KB

When it exceeds 5KB, the following effects will be produced:

3.6. Spring boot log custom configuration file

be careful:

If a custom log configuration file is used, application The log configuration in YML will fail.

If you use a configuration like spring profiles, you must change the file name of the log file to: logback spring XML, because springProfiles is provided by SpringBoot, logback The XML file will only make logback XML loading, while logback spring XML will be loaded by SpringBoot and logback at the same time.

Custom variables in configuration file

<?xml version="1.0" encoding="UTF-8" ?>
<configuration>
    <!-- Configuration variable -->
    <springProperty scope="context" name="dateFormat" source="logging.pattern.dateformat"
        defaultValue="-yyyy-MM-dd HH:mm:ss.SSS"/>

    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <!-- {100} Currently, 100 characters can be output -->
            <pattern>%d{${dateFormat}} [%thread] %-5level %logger{100} - %msg%n</pattern>
        </encoder>
    </appender>
    <!-- You can control log output more finely -->
    <logger name="cool.ale" level="trace"></logger>
    <!-- Log level of the root directory -->
    <root level="error">
        <appender-ref ref="STDOUT" />
    </root>
</configuration>

Where source="logging.pattern.dateformat" means to go to application first Find logging. In the YML file pattern. Dateformat configuration. If it is not found, the format specified by the defaultValue property will be used.

3.7. SpringBoot switching log framework

We need to write the following configuration in the pom file, because SpringBoot can only have one bridge when cooperating with the log framework, so when we add other framework configurations, we need to remove the default log framework bridge provided by web starter, as shown below:
It is divided into the following three steps:
1. Remove the bridge provided by logback
2. Add the bridge that needs to switch the log framework
3. Add the corresponding log configuration file

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    <!-- Eliminate starter-logging that is logback Dependence of -->
    <exclusions>
        <exclusion>
            <artifactId>spring-boot-starter-logging</artifactId>
            <groupId>org.springframework.boot</groupId>
        </exclusion>
    </exclusions>
</dependency>

<!-- log4j2 Scene launcher for -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-log4j2</artifactId>
</dependency>

We can also generate excluded parts, as shown below:

Topics: Java Spring Spring Boot Back-end