Be serious about writing, not clickbait.

The article is available at Github.com/niumoo/Java… And program ape Alang’s blog, point attention, don’t get lost.

Note: This Spring Boot series of articles is based on Spring Boot version V2.1.1.release, which may vary slightly.

preface

The Spring framework chooses to use JCL as the default logging output. Spring Boot uses SLF4J with LogBack by default. Which logging framework should we use in our project? What do we do when different logging frameworks are used for different third-party jars?

1. Log framework

The importance of logging to an application is self-evident, whether it is to record health or trace online problems, log analysis is indispensable, there are a variety of logging frameworks in the Java world, Such as JUL, Log4j, Log4j2, Commons Loggin, Slf4j, Logback, etc. Log4j, Log4j2, Slf4j, Slf4j, Slf4j, Slf4j, Slf4j

2. Use of SLF4

Logging implementation classes should not be used directly during development; instead, an abstraction layer of logging should be used. Specific referenceSLF4J official. The following figure is an official example of SLF4J combined with various logging frameworks. It is clear from the figure that the SLF4J API will always be used as the face of logging, directly applied to applications.

At the same time, SLF4 official gives a simple example.

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

public class HelloWorld {
  public static void main(String[] args) {
    Logger logger = LoggerFactory.getLogger(HelloWorld.class);
    logger.info("Hello World"); }}Copy the code

Note that the SLF4J JAR and the logging framework implementation JAR are imported for the system. Since each logging implementation framework has its own configuration file, after using SLF4, the configuration file will still use the one that implements the logging framework.

3. Use of a unified logging framework

What if you want to set up a unified logging framework for your project?

In SLF4J official, also give us reference examples.

The figure shows a way to unify the logging framework by replacing it with a jar that is identical to the logging framework class to avoid errors from the original third-party JAR, which actually uses the SLF4J API. The logs in the project can then be logged using the SLF4J API in conjunction with the framework of your choice. The steps to use the unified logging framework are summarized as follows:

  1. Exclude other logging frameworks in the system.
  2. Replace the logging framework to be replaced with a tundish.
  3. Import the SLF4J implementation of our choice.

4. Relationship between Spring Boot logs

4.1. Exclude other logging frameworks

In order to unify the use of the logging framework, the first step is to exclude other logging frameworks. It is clear from Spring Boot’s Maven dependencies that Spring Boot excludes other logging frameworks.We can rule out dependencies by following the diagram.

4.2. Unified framework introduces replacement packs

In fact, Spring Boot is also using SLF4J+logback logging framework combination, Viewing the Maven dependencies of the Spring Boot project, you can see that spring-boot-starter, the core launcher of Spring Boot, introduces Spring-boot-starter-logging.

    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-logging</artifactId>
      <version>2.1.1. RELEASE</version>
      <scope>compile</scope>
    </dependency>
Copy the code

The Maven dependency on Spring-boot-starter-logging mainly introduces logback-classic (which includes the logback implementation of the logging framework), Log4j-to-slf4j (the log4j logging framework authors did not have a logging abstraction layer in mind when they developed the framework, so there are tools to convert log4j to SLF4J), Jul-to-slf4j (Java’s native logging framework converts to SLF4J).

  <dependencies>
    <dependency>
      <groupId>ch.qos.logback</groupId>
      <artifactId>logback-classic</artifactId>
      <version>1.2.3</version>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>org.apache.logging.log4j</groupId>
      <artifactId>log4j-to-slf4j</artifactId>
      <version>2.11.1</version>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>jul-to-slf4j</artifactId>
      <version>1.7.25</version>
      <scope>compile</scope>
    </dependency>
  </dependencies>
Copy the code

From the above analysis, Spring Boot’s use of the logging framework is clear, we use the IDEA tool to check Maven dependencies, you can clearly see the logging framework reference. If you do not have the IDEA tool, you can also use the Maven command to view dependencies.

mvn dependency:tree
Copy the code

Thus, Spring Boot can automatically adapt to the logging framework, and the underlying useSLF4 + LogBackLogging, if we introduce other frameworks ourselves, we need to exclude their logging frameworks.

5. Use Spring Boot logs

5.1. Log levels and formats

Spring Boot already uses SLF4J + LogBack by default. So we can use SLF4J + Logback for logging without doing anything extra. Write Java test classes to test.

import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

/ * * * < p > * test log output, * SLF4J logging level raised to trace, debug, info, warn, error * *@Author niujinpeng
 * @Date2018/12/11 ye: * /
@RunWith(SpringRunner.class)
@SpringBootTest
public class LogbackTest {
    
    Logger logger = LoggerFactory.getLogger(getClass());

    @Test
    public void testLog(a) {
        logger.trace("The Trace log...");
        logger.debug("The Debug log...");
        logger.info("The Info log...");
        logger.warn("Warn log...");
        logger.error("The Error log..."); }}Copy the code

Known log levels from small to large are trace < debug < info < warn < error. The output is as follows. The default Spring Boot log level is INFO.

2018-12-11 23:02:58.028 [main] INFO n.c.botwoot. 2018-12-11 23:02:58.029 [main] WARN N.C.botwoot.LogbackTest - WARN... 2018-12-11 23:02:58.029 [main] ERROR n.c.botwoot.LogbackTest - ERROR... 2018-12-11 23:02:58.029 [main] ERROR n.c.botwoot.Copy the code

The Spring Boot default log format is.

%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n
#% d {MM - dd yyyy - HH: MM: ss. The SSS}
#%thread Specifies the name of the thread
#%-5level Log level Displays 5 characters in width from the left
#% logger {50} class name
#% MSG %n Add a newline to the log information
Copy the code

Why is Spring Boot’s default log output format this?We can find the answer in Spring Boot’s source code.

5.2 Customizing Log Output

Logging configurations can be written directly in the configuration file.

# log configuration
# specify the log level for a specific package
logging.level.net.codingme=debug
Console and log file output format
logging.pattern.console=%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n
logging.pattern.file=%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n
Log file size
logging.file.max-size=10MB
The log duration to be retained
logging.file.max-history=10
Log output path, default file spring.log
logging.path=systemlog
#logging.file=log.log
Copy the code

The log output path can be defined using logging.file or logging.path. The relationship between the two is shown in the following table.

logging.file logging.path example describe
(no) (no) Only console records.
The specific file (no) my.log Writes to the specified log file, whose name can be exact location or relative to the current directory.
(no) Specific directory /var/log writespring.logSpecifies the directory whose name can be exact location or relative to the current directory.

6. Replace the logging framework

Since the Log4j logging framework has fallen into disrepair and was not well written by the original authors, here is how to replace the logging framework with Log4j2. According to the official website, we need to choose between Log4j2 and logging, so modify poM as follows.

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

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

The article code has been uploaded to the GitHub Spring Boot logging system.

After < >

Hello world 🙂

I am a lang, lang of the moon, a technical tool person who moves bricks every day. Personal website: www.wdbyte.com If you want to subscribe, you can follow the public account of “Procedural Ape Alang”, or the blog of procedural ape Alang, or add me on wechat (WN8398).

This article has also been compiled at GitHub.com/niumoo/Java… Welcome Star.