Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the ways to use Spring Boot logs

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly introduces "what is the use of Spring Boot log". In daily operation, I believe that many people have doubts about the use of Spring Boot log. The editor consulted all kinds of data and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubts about "what is the use of Spring Boot log?" Next, please follow the editor to study!

1. Java log overview

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

1.1 General Overview

The following figure shows a good example of the logging system in Java:

As you can see, the logging framework in Java is mainly divided into two categories: log facade and log implementation.

Log facade

The log facade defines the interface specification of a set of logs, which does not provide the underlying specific implementation logic. Apache Commons Logging and Slf4j fall into this category.

Log 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 console, etc.). Log4j, Log4j2, Logback and Java Util Logging fall into this category.

Separating the log facade from the log implementation is actually a typical facade mode, which allows specific businesses to switch freely between different log implementation frameworks without changing any code. Developers only need to master the log facade API.

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

So can the logging framework be used alone?

Technically, of course, it's fine, but we don't usually do this because it's not maintainable and it's not easy to scale later. For example, A develops a toolkit that uses Log4j to print logs, and B references this toolkit, but B likes to print logs using Logback. At this time, a business will use two or more log frameworks, and developers also need to maintain configuration files for multiple logs. So we all use the log facade to print the log.

1.2 Log level

The advantage of using the log level is that by adjusting the level, you can mask a lot of debugging-related log output. Different logging implementations define different logging levels, but they are more or less the same.

Java Util Logging

Java Util Logging defines seven log levels, from severe 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 log levels (excluding OFF and ALL, it can be said to be divided into six levels), from severe to normal:

OFF: the highest level, used to turn off all logging.

FATAL: major error, at this level you can stop the program directly.

ERROR: print error and exception messages, which you can use if you don't want to output too many logs.

WARN: warning prompt.

INFO: some important information used to output programs running in a production environment should not be misused.

DEBUG: used to print some running information during the development process.

TRACE

The lowest level of ALL, used to open all logging.

Logback

The Logback log level is relatively simple, from severe to normal:

ERROR

WARN

INFO

DEBUG

TRACE

1.3 Comprehensive comparison

The Java Util Logging system reads the configuration file and completes initialization when JVM starts, and once the application starts running, the configuration cannot be modified. In addition, this logging implementation configuration is not very convenient, and parameters can only be passed when JVM starts, as shown below:

-Djava.util.logging.config.file=.

Because of these limitations, Java Util Logging is not widely used.

Although the configuration of Log4j is tedious, once the configuration is complete, it is very easy to use. You only need to put the relevant configuration files under classpath. In many cases, Log4j configuration files can be used repeatedly in different projects.

Log4j can be used with Apache Commons Logging, and Apache Commons Logging automatically searches for and uses Log4j, and if no Log4j is found, use Java Util Logging.

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

Logback is the native implementation framework of Slf4j, and it is also the work of the author of Log4j (Ceki G ü lc ü), but it has more advantages, features, and stronger performance than Log4j.

1.4 Best practices

If you don't want to add any dependencies, use the logging interface already provided by the Java Util Logging or framework container.

If you care about performance, it is recommended: Slf4j + Logback.

If Log4j is already used in the project and no performance problems are found, the recommended combination is: Slf4j + Log4j2.

2. Spring Boot log implementation

Spring Boot uses Apache Commons Logging as the internal logging framework facade, which is only a logging interface, which needs to be specified for the corresponding logging implementation in practical applications.

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 changeable character, we search the project globally: The following profiles are active, and the results are 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, log dependencies are automatically added as long as the following web dependencies are added:

Org.springframework.boot spring-boot-starter-web2.1 Spring Boot log configuration

Spring Boot's logging system automatically selects the appropriate logging configuration according to the content under classpath, and Logback is preferred in this process.

If the developer needs to modify the log level, you only need to configure it in the application.properties file in the form of logging.level prefix + package name, such as the following:

Logging.level.org.springframework.web=debuglogging.level.org.hibernate=error

If you want to output the log to a file, you can specify the log file name with the following configuration:

Logging.file.name=javaboy.log

Logging.file.name can specify only the log file name or the full path to the log file, such as the following:

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

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

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

If you want to fine-manage the logs output to a file, there are also some properties that can be configured:

Logging.logback.rollingpolicy.file-name-pattern: the file name of the log archive. After the log file reaches a certain size, it will be compressed and archived automatically.

Logging.logback.rollingpolicy.clean-history-on-start: whether to perform archive management when the application is started.

Logging.logback.rollingpolicy.max-file-size: the upper limit of log file size. After reaching this limit, it will be automatically compressed.

Logging.logback.rollingpolicy.total-size-cap: the maximum size that a log file can hold before it is deleted.

Logging.logback.rollingpolicy.max-history: the number of days that the log file is saved.

If you are interested in archiving the log file, you can try it yourself. You can first reduce the max-file-size attribute to make it easy to see the effect:

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

Then add the following interfaces:

@ RestControllerpublic 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"); } }} 访问该接口,可以看到最终生成的日志文件被自动压缩了:

Log grouping can also be configured in application.properties.

Log grouping allows you to put related logger 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

Then uniformly manage all logger in the tomcat group:

Logging.level.tomcat=TRACE

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

However, only some very simple configuration of logs can be implemented in application.properties. If you want to achieve a more fine-grained log configuration, you need to use the native configuration of log implementation, such as the classpath:log4j.xml of Logback's classpath:logback.xml,Log4j. If these log configuration files exist under classpath, by default, Spring Boot will automatically load these configuration files.

2.2 Logback configuration 2.2.1 basic configuration

There are two default Logback profile names:

Logback.xml: this configuration file is directly loaded by the logging framework.

Logback-spring.xml: this configuration file is not directly loaded by the logging framework, but is parsed by Spring Boot, which can use the advanced Profile features of Spring Boot.

Four default configuration files are provided for Logback in Spring Boot, which are located in org/springframework/boot/logging/logback/,:

Defaults.xml: provides common log configuration, log output rules, etc.

Console-appender.xml: add a ConsoleAppender using CONSOLE_LOG_PATTERN.

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 profiles when customizing, or you can not use them. A typical logback.xml file is as follows (resources/logback.xml):

You can import configuration files already provided by Spring Boot through include, or you can customize them.

2.2.2 Export to a file

If you want to disable log output from the console and output the log contents to a file instead, we can customize a logback-spring.xml file and introduce the file-appender.xml file mentioned earlier.

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

2.3 Log4j configuration

If there is a dependency on Log4j2 under classpath, Spring Boot will configure it automatically.

Of course, there is no Log4j2 dependency under classpath by default. If you want to use Log4j2, you can exclude the existing Logback, and then introduce Log4j2, as follows:

Org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter-logging org.springframework.boot spring-boot-starter-log4j2

It is relatively easy to configure Log4j2. Create a new log4j2.xml file in the reources directory as follows:

Logging logs/$ {app_name}

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

Then different levels of logs are processed separately through several different RollingFile, and different levels of logs are output to different files and compressed according to their respective naming methods.

This configuration is more stylized, friends can save it to make an IntelliJ IDEA template for daily use.

At this point, the study on "what is the use of Spring Boot logs" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report