编程知识 cdmana.com

Spring boot logs all kinds of posture, it's time to clear!

@[toc]
I recorded a video to share with you Spring Boot Log problems , But I always feel almost mean , Therefore, SongGe intends to use an article to smooth it out with you Java Log problem in , By the way, we put Spring Boot The problem of log in is also clear .

1. Java Log overview

Speaking of Java journal , Many beginners may be confused , Because there are so many things involved here :Apache Commons LoggingSlf4jLog4jLog4j2LogbackJava Util Logging wait , What is the role of each of these frameworks ? What's the difference between them ?

1.1 General overview

This is a good illustration of Java Log system in :

You can see ,Java There are two main types of log frameworks in : Log facade and Log implementation .

Log facade

Log facade defines a set of log interface specifications , It does not provide the underlying implementation logic .Apache Commons Logging and Slf4j It belongs to this category .

Log implementation

Log implementation is the specific implementation of log , Including log level control 、 Log print format 、 Log output form ( Output to database 、 output to a file 、 Output to console, etc ).Log4jLog4j2Logback as well as Java Util Logging It belongs to this category .

Separating log facade from log implementation is a typical facade pattern , This way allows specific businesses to switch freely between different log implementation frameworks , Without changing any code , Developers only need to master the log facade API that will do .

Log facade cannot be used alone , It must be used in conjunction with a specific logging implementation framework .

So whether the logging framework can be used alone ?

Technically, of course , But we don't usually do this , Because it's not very maintainable , And it's not easy to expand later . for example A Developed a toolkit to use Log4j Print log ,B It's a reference to this toolkit , however B Love to use Logback Print log , There will be a business that uses two or more logging frameworks , Developers also need to maintain multiple log profiles . So we all use the log facade to print the log .

1.2 The level of logging

The benefit of using the log level is that , Adjust level , You can block a lot of debugging related log output . Different log implementations define different log levels , But they're all the same .

Java Util Logging

Java Util Logging Defined 7 Log level , From serious to average, the order is :

  • SEVERE
  • WARNING
  • INFO
  • CONFIG
  • FINE
  • FINER
  • FINEST

Because the default level is INFO, therefore INFO Log below level , It's not going to print out .

Log4j

Log4j Defined 8 Log level ( remove OFF and ALL, It can be divided into 6 A level ), From serious to average, the order is :

  • OFF: At the highest level , Used to turn off all logging .
  • FATAL: Big mistake , This level can stop the program directly .
  • ERROR: Print error and exception information , If you don't want to output too many logs , You can use this level .
  • WARN: Warning tips .
  • INFO: It is used to output some important information of program running in production environment , Can't abuse .
  • DEBUG: It is used to print some operation information in the development process .
  • TRACE
  • ALL The lowest level , Used to turn on all logging .

Logback

Logback Log level is relatively simple , From serious to average, the order is :

  • ERROR
  • WARN
  • INFO
  • DEBUG
  • TRACE

1.3 Comprehensive comparison

Java Util Logging The system is in JVM At startup, read the configuration file and complete the initialization , Once the application starts running , You can't modify the configuration . in addition , This kind of log implementation configuration is not very convenient , Only in JVM Pass parameters at startup , Like this :

-Djava.util.logging.config.file=<config-file-name>.

Because of these limitations , Lead to Java Util Logging Not widely used .

Log4j Although the configuration is cumbersome , But once the configuration is complete , It's very convenient to use , Just put the relevant configuration files in classpath Then you can . In many cases ,Log4j We can use it repeatedly in different projects .

Log4j You can talk to Apache Commons Logging Use it with ,Apache Commons Logging Will automatically search and use Log4j, If not found Log4j, Reuse Java Util Logging.

Than Log4j + Apache Commons Logging The combination is more popular Slf4j + Logback Combine .

Logback yes Slf4j Native implementation framework of , It also comes from Log4j author (Ceki Gülcü) In the hands of , But compared to the Log4j, It has more advantages 、 Features and greater performance .

1.4 Best practices

  • If you don't want to add any dependencies , Use Java Util Logging Or the logging interface provided by the framework container .
  • If you care about performance , recommend :Slf4j + Logback.
  • If the project has already used Log4j And no performance problems were found , The recommended combination is :Slf4j + Log4j2.

2. Spring Boot Log implementation

Spring Boot Use Apache Commons Logging As an internal log framework facade , It's just a log interface , In practical application, it is necessary to specify the corresponding log implementation for this interface .

Spring Boot The default logging implementation is Logback. This is very easy to see : Start one at random Spring Boot project , Find a log line from the console , Like the following :

Considering the final prod It's a character that can be changed , We search the project globally :The following profiles are active, give the result as follows :

In the line of log output debug. And then start the project again , Here's the picture :

At this point, we can see that the real log implementation is Logback.

Other things like Java Util LoggingLog4j Other framework ,Spring Boot There's also good support .

stay Spring Boot In the project , Just add the following web rely on , Log dependencies are added automatically :

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

2.1 Spring Boot Log configuration

Spring Boot The log system will automatically follow classpath Select the appropriate log configuration for the following content , The first choice in this process is Logback.

If the developer needs to change the log level , Only need application.properties Through the file logging.level Prefix + Package name Configuration in the form of , Like the following :

logging.level.org.springframework.web=debug
logging.level.org.hibernate=error

If you want to output the log to a file , The log file name can be specified by the following configuration :

logging.file.name=javaboy.log

logging.file.name You can only specify the log file name , You can also specify the full path of the log file , Like the following :

logging.file.name=/Users/sang/Documents/javaboy/javaboy.log

If you just want to redefine the path of the output log file , You can also use logging.file.path attribute , as follows :

logging.file.path=/Users/sang/Documents/javaboy

If you want to fine-grained manage the log output to the file , The following properties can be configured :

  • logging.logback.rollingpolicy.file-name-pattern: The file name of the log archive , After the log file reaches a certain size , Automatic compression archive .
  • logging.logback.rollingpolicy.clean-history-on-start: Whether to manage the archive when the application is started .
  • logging.logback.rollingpolicy.max-file-size: Maximum log file size , When that limit is reached , It will automatically compress .
  • logging.logback.rollingpolicy.total-size-cap: Before the log file is deleted , The maximum size that can hold .
  • logging.logback.rollingpolicy.max-history: The number of days the log file is saved .

Log file archiving this , You can try it yourself , You can start by putting max-file-size Attribute down , It's easy to see the effect :

logging.logback.rollingpolicy.max-file-size=1MB

Then add the following interface :

@RestController
public class HelloController {
    private static final Logger logger = getLogger(HelloController.class);
    @GetMapping("/hello")
    public void hello() {
        for (int i = 0; i < 100000; i++) {
            logger.info("hello javaboy");
        }
    }
}

Access the interface , You can see that the final generated log file is automatically compressed :

application.properties You can also configure log grouping in .

Log grouping can put the relevant logger Put it into a group and manage it in a unified way .

For example, we can define a tomcat Group :

logging.group.tomcat=org.apache.catalina,org.apache.coyote, org.apache.tomcat

And then unified management tomcat All of the... In the group logger:

logging.level.tomcat=TRACE

Spring Boot Two log groups are also predefined in web and sql, as follows :

But in the application.properties Can only achieve some very simple log configuration , If you want to achieve more fine-grained log configuration , Then you need to use the native configuration of log implementation , for example Logback Of classpath:logback.xml,Log4j Of classpath:log4j.xml etc. . If these log configuration files exist in classpath Next , So by default ,Spring Boot These configuration files will be loaded automatically .

2.2 Logback To configure

2.2.1 Basic configuration

default Logback There are two types of configuration file names :

  • logback.xml: This configuration file is loaded directly by the logging framework .
  • logback-spring.xml: This configuration file is not loaded directly by the logging framework , But by the Spring Boot To parse the log configuration , have access to Spring Boot Advanced Profile function .

Spring Boot In Chinese, it means Logback Four default configuration files are provided , Position in org/springframework/boot/logging/logback/, Namely :

  • defaults.xml: Provides a common log configuration , Log output rules, etc .
  • console-appender.xml: Use CONSOLE_LOG_PATTERN Add one ConsoleAppender.
  • file-appender.xml: Add one RollingFileAppender.
  • base.xml: For compatibility with older versions Spring Boot And what it provides .

If you need to customize logback.xml file , You can use these default profiles for customization , You can also not use . A typical logback.xml The documents are as follows (resources/logback.xml):

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <include resource="org/springframework/boot/logging/logback/defaults.xml"/>
    <include resource="org/springframework/boot/logging/logback/console-appender.xml" />
    <root level="INFO">
        <appender-ref ref="CONSOLE" />
    </root>
    <logger name="org.springframework.web" level="DEBUG"/>
</configuration>

Can pass include introduce Spring Boot The configuration file that has been provided , You can also customize it .

2.2.2 output to a file

If you want to disable log output from the console , Instead, output the log content to a file , We can customize one logback-spring.xml file , And introduce what I said earlier file-appender.xml file .

Like this (resources/logback-spring.xml):

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <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/file-appender.xml" />
    <root level="INFO">
        <appender-ref ref="FILE" />
    </root>
</configuration>

2.3 Log4j To configure

If classpath There is Log4j2 Dependence ,Spring Boot Will automatically configure .

By default classpath Of course, there is no such thing Log4j2 Dependence , If you want to use Log4j2, You can exclude what you already have Logback, And then introduce Log4j2, as follows :

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    <exclusions>
        <exclusion>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-logging</artifactId>
        </exclusion>
    </exclusions>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-log4j2</artifactId>
</dependency>

Log4j2 It's easier to configure , stay reources New under the directory log4j2.xml file , The contents are as follows :

<?xml version="1.0" encoding="UTF-8"?>
<configuration status="warn">
    <properties>
        <Property name="app_name">logging</Property>
        <Property name="log_path">logs/${app_name}</Property>
    </properties>
    <appenders>
        <console name="Console" target="SYSTEM_OUT">
            <PatternLayout pattern="[%d][%t][%p][%l] %m%n" />
        </console>
        <RollingFile name="RollingFileInfo" fileName="${log_path}/info.log"
                     filePattern="${log_path}/$${date:yyyy-MM}/info-%d{yyyy-MM-dd}-%i.log.gz">
            <Filters>
                <ThresholdFilter level="INFO" />
                <ThresholdFilter level="WARN" onMatch="DENY"
                                 onMismatch="NEUTRAL" />
            </Filters>
            <PatternLayout pattern="[%d][%t][%p][%c:%L] %m%n" />
            <Policies>
                <TimeBasedTriggeringPolicy interval="1" modulate="true" />
                <SizeBasedTriggeringPolicy size="2 MB" />
            </Policies>
            <DefaultRolloverStrategy compressionLevel="0" max="10"/>
        </RollingFile>
        <RollingFile name="RollingFileWarn" fileName="${log_path}/warn.log"
                     filePattern="${log_path}/$${date:yyyy-MM}/warn-%d{yyyy-MM-dd}-%i.log.gz">
            <Filters>
                <ThresholdFilter level="WARN" />
                <ThresholdFilter level="ERROR" onMatch="DENY"
                                 onMismatch="NEUTRAL" />
            </Filters>
            <PatternLayout pattern="[%d][%t][%p][%c:%L] %m%n" />
            <Policies>
                <TimeBasedTriggeringPolicy interval="1" modulate="true" />
                <SizeBasedTriggeringPolicy size="2 MB" />
            </Policies>
            <DefaultRolloverStrategy compressionLevel="0" max="10"/>
        </RollingFile>

        <RollingFile name="RollingFileError" fileName="${log_path}/error.log"
                     filePattern="${log_path}/$${date:yyyy-MM}/error-%d{yyyy-MM-dd}-%i.log.gz">
            <ThresholdFilter level="ERROR" />
            <PatternLayout pattern="[%d][%t][%p][%c:%L] %m%n" />
            <Policies>
                <TimeBasedTriggeringPolicy interval="1" modulate="true" />
                <SizeBasedTriggeringPolicy size="2 MB" />
            </Policies>
            <DefaultRolloverStrategy compressionLevel="0" max="10"/>
        </RollingFile>
    </appenders>
    <loggers>
        <root level="info">
            <appender-ref ref="Console" />
            <appender-ref ref="RollingFileInfo" />
            <appender-ref ref="RollingFileWarn" />
            <appender-ref ref="RollingFileError" />
        </root>
    </loggers>
</configuration>

First, in the properties The application name and log file location are specified in the node .

And then through a few different RollingFile Handle different levels of logs separately , Different levels of logs will be output to different files , And compress them according to their own naming methods .

This configuration is more stylized , You can keep them and make them IntelliJ IDEA Template for daily use .

3. Summary

All right. , This is what SongGe and his friends share Spring Boot Log , On the whole, it's not difficult , Friends can have a taste of it .

Last , SongGe also collected 50+ Project requirements documents , If you want to be a project, you may as well have a look ~





Requirements document address :gitee.com/lenve/javadoc

Click to see more

版权声明
本文为[osc_ u61lmlkv]所创,转载请带上原文链接,感谢
https://cdmana.com/2020/12/20201225083918585p.html

Scroll to Top