[TOC] : Spring Boot logging is a problem in Java. It is a problem in Java. It is a problem in Java.

1. Java Log Overview

When it comes to Java Logging, many beginners may be confused because there are so many things involved: Apache Commons Logging, Slf4j, Log4j, Log4j2, Logback, Java Util Logging, and so on. What does each of these frameworks do? What’s the difference between them?

1.1 General overview

Here’s a good example of logging in Java:

As you can see, logging frameworks in Java fall into two main categories: logging facade and logging implementation.

Logging facade

The logging facade defines an interface specification for a set of logs that does not provide the underlying implementation logic. Apache Commons Logging and Slf4j fall into this category.

The logging implementation

Log implementation is the specific implementation of log, including log level control, log printing format, log output form (output to database, output to file, output to the console, etc.). Log4j, Log4j2, Logback, and Java Util Logging fall into this category.

Separating the logging facade from the logging implementation is a typical facade pattern that allows specific businesses to switch between different logging implementation frameworks without changing any code. Developers only need to master the logging facade API.

The logging facade cannot be used alone; it must be used in conjunction with a specific logging implementation framework.

Can the logging framework be used on its own?

Technically it’s fine, but we don’t usually do this because it’s not maintainable and it’s not scalable. For example, USER A develops A toolkit to use Log4j to print logs, and user B references this toolkit, but user B prefers to use Logback to print logs. In this case, one service uses two or more logging frameworks, and the developer also needs to maintain configuration files for multiple logs. So we all use the log facade to print the log.

1.2 Log Levels

The advantage of using log levels is that by adjusting the level, you can mask a lot of debug related log output. Different logging implementations define different logging levels, but they are all similar.

Java Util Logging

Java Util Logging defines seven Logging levels, from critical to normal:

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

Because the default level is INFO, logs below the INFO level will not be printed.

Log4j

Log4j defines eight logging levels (six, excluding OFF and ALL), from critical to common:

  • OFF: indicates the highest level. It is used to disable all logging.
  • FATAL: Stop the program.
  • ERROR: Prints errors and exceptions. You can use this level if you do not want to output too many logs.
  • WARN: Indicates a warning.
  • INFO: output important information about program running in the production environment. Do not abuse it.
  • DEBUG: Prints running information during development.
  • TRACE
  • ALL Indicates the lowest level. It is used to enable ALL logging.

Logback

Logback log levels are as follows:

  • ERROR
  • WARN
  • INFO
  • DEBUG
  • TRACE

1.3 Comprehensive comparison

The Java Util Logging system reads and initializes the configuration file at JVM startup and cannot modify the configuration once the application is running. In addition, this logging implementation configuration is not very convenient, and only parameters can be passed at JVM startup, like the following:

. - Djava. Util. Logging. Config file = < config file - - the name >.Copy the code

Due to these limitations, Java Util Logging is not widely used.

Log4j is cumbersome to configure, but once it is configured, it is very easy to use. You just need to put the relevant configuration files in your CLASspath. In many cases, Log4j configuration files can be used repeatedly in different projects.

Log4j can be used in conjunction with Apache Commons Logging, which automatically searches for and uses Log4j and, if Log4j is not found, Java Util Logging.

More popular than Log4j + Apache Commons Logging is Slf4j + Logback.

Logback is the native implementation framework of Slf4j and was also written by The author of Log4j (Ceki Gulcu), but it has more advantages, features, and performance than Log4j.

1.4 Best Practices

  • If you don’t want to add any dependencies, useJava Util LoggingOr the logging interface that the framework container already provides.
  • If you care about performance, recommend:Slf4j + Logback.
  • If it’s already used in the projectLog4jIf no performance problem is found, the recommended combination is as follows:Slf4j + Log4j2.

2. Spring Boot log implementation

Spring Boot uses Apache Commons Logging as the internal Logging framework facade. It is just a Logging interface that needs to be specified for the corresponding Logging implementation.

The default logging implementation for Spring Boot is Logback. This is easy to see: Start any Spring Boot project and find a log line from the console, such as the following:

Considering that The final prod is a variable character, we searched globally in The project: The following profiles are active, and The result was as follows:

Debug on the line of log output. Then start the project again as shown below:

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

Other frameworks, such as Java Util Logging and Log4j, are also well supported by Spring Boot.

In the Spring Boot project, logging dependencies are automatically added whenever the following Web dependencies are added:

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

2.1 Spring Boot Log Configuration

The Spring Boot logging system automatically selects an appropriate log configuration based on the contents in clasSPath, and Logback is preferred.

If the developer needs to change the logging level, it can be configured in the application.properties file using the logging.level prefix + package name, for example:

logging.level.org.springframework.web=debug
logging.level.org.hibernate=error
Copy the code

If you want to export logs to a file, you can specify the log file name using the following configuration:

logging.file.name=javaboy.log
Copy the code

Logging.file.name can specify only the log file name or the full log file path, as shown in the following example:

logging.file.name=/Users/sang/Documents/javaboy/javaboy.log
Copy the code

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

logging.file.path=/Users/sang/Documents/javaboy
Copy the code

If you want to fine-tune log output to a file, you can configure the following properties:

  • Logging. Logback. Rollingpolicy. File – name – the pattern: log archive file name, the log file after reach a certain size, automatically compressed archive.
  • Logging. Logback. Rollingpolicy. Clean – history – on – start: whether in application startup archive management.
  • Logging. Logback. Rollingpolicy. Max – file – size: log file size limit, after reaching the ceiling, automatically compressed.
  • Logging. Logback. Rollingpolicy. Total – size – cap: before the log file to be deleted, can accommodate the largest size.
  • Logging. Logback. Rollingpolicy. Max – history: the log file to save the number of days.

Max file size = Max file size = Max file size = Max file size = Max file size = Max file size = Max file size

logging.logback.rollingpolicy.max-file-size=1MB
Copy the code

Then add the following interface:

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

Accessing this interface, you can see that the resulting log file is automatically compressed:

You can also configure log groups in application.properties.

Log grouping can put related loggers into a group for unified management.

For example, we can define a Tomcat group:

logging.group.tomcat=org.apache.catalina,org.apache.coyote, org.apache.tomcat
Copy the code

Then uniformly manage all loggers in the Tomcat group:

logging.level.tomcat=TRACE
Copy the code

Spring Boot also predefined two log groups, Web and SQL, as follows:

However, you can only implement very simple logging configurations in application.properties. If you want to implement more granular logging configurations, you need to use native logging configurations, such as Logback’s classpath:logback.xml, Log4j classpath:log4j.xml, etc. If these log profiles exist in the CLASspath, Spring Boot automatically loads them by default.

2.2 Logback configuration

2.2.1 Basic Configuration

There are two default Logback 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. Instead, Spring Boot parses the logging configuration, using Spring Boot’s advanced Profile feature.

In the Spring the Boot offers Logback four configuration files, the default position in the org/springframework/Boot/logging/Logback /, respectively is:

  • Defaults.xml: provides common logging configuration, logging output rules, and so on.
  • Console-appender. XML: Use CONSOLE_LOG_PATTERN to add a ConsoleAppender.
  • File-appender. XML: Add a RollingFileAppender.
  • Base.xml: provided for compatibility with older versions of Spring Boot.

If you need to customize the logback.xml file, you can use these default configuration files for customization or not. A typical logback. XML file looks like this (resources/logback.xml) :


      
<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>
Copy the code

You can include or customize configuration files provided by Spring Boot.

2.2.2 Output to a File

If you want to disable console logging and export the log content to a file instead, you can customize a logback-spring. XML file and introduce the file-appender.xml file mentioned earlier.

Like the following (resources/logback-spring.xml) :


      
<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>
Copy the code

2.3 Log4j configuration

If the Log4j2 dependency exists in the CLASspath, Spring Boot will automatically configure it.

By default, Log4j2 does not exist in the classpath. If you want to use Log4j2, you can exclude the existing Logback and 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>
Copy the code

Log4j2 is easy to configure. Create a new log4j2. XML file in the reources directory.


      
<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>
Copy the code

The application name and log file location are first specified in the Properties node.

The logs of different levels are then processed through several different rollingfiles. The logs of different levels are output to different files and compressed according to their names.

This configuration is stylized, and you can save it to make IntelliJ IDEA template for daily use.

3. Summary

Well, this is the Spring Boot log songgo and friends to share, the overall is not difficult, friends can carefully taste a taste.

Finally, Songgo also collected more than 50 project requirements documents, if you want to do a project to practice friends can look at it

Requirements documentation address: gitee.com/lenve/javad…