Preface
Logs are one of the important debugging tools during the operation of software systems. In Spring Boot, the configuration and management of logs are relatively simple and flexible. This article will explain in detail how to configure logs in a Spring Boot project.
1. Overview of Spring Boot Log Framework
Spring Boot has built-in support for a variety of log frameworks, and the default is SLF4J (Simple Logging Facade for Java) combined with Logback as log implementation. SLF4J is a log abstraction layer that allows developers to choose different log implementations, while Logback is a very efficient log implementation. Spring Boot also supports other common logging frameworks, such as Log4j2, Java Util Logging (JUL), etc.
By default, Spring Boot projects output logs in the console, and developers can customize settings by modifying configuration files, such as outputting logs to files, adjusting log levels, etc.
2. Log level and configuration
2.1 Log Level
Spring Boot supports the following common log levels, arranged from high to low by priority:
- ERROR: A serious error, a problem that generally needs to be fixed immediately.
- WARN: Warning, events that may cause problems.
- INFO: Important information during system operation is usually information about system state changes.
- DEBUG: Detailed debugging information for development and diagnosis.
- TRACE: More fine-grained debugging information, more detailed than DEBUG.
Each log level will contain logs with higher priority than it. For example, if you set the log level toWARN
, it will printWARN
andERROR
Level log.
2.2 Log level configuration
We canor
Configure log level. Here is an example of configuring the log level:
# Set the global log level to INFO=INFO # Set the log level of a specific package to DEBUG=DEBUG
If you use YAML format, you can configure it like this:
logging: level: root: INFO : DEBUG
3. Log file output and scrolling configuration
In production environments, it is common to output logs to files. Spring Boot provides very flexible log file configuration options, including the path to configure log file, the scrolling strategy of log file, etc.
3.1 Log file output
To output the log to a file, just set it in the configuration fileor
Parameters:
# Export the log to the specified file=logs/
Or just specify the log directory, Spring Boot will automatically generate files:
# Export the log to the specified directory=logs
3.2 Log file scrolling
Log file scrolling means that when the log file reaches the specified size or time, the system will rename and archive the old log file and generate a new log file. This can prevent excessive log files from affecting system performance. Logback allows the definition of scrolling policies through configuration files.
Here is a simple Logback configuration example (), which can be used to implement the size scrolling of log files:
<configuration> <appender name="FILE" class=""> <file>logs/</file> <rollingPolicy class=""> <maxFileSize>10MB</maxFileSize> </rollingPolicy> <encoder> <pattern>%d{yyyy-MM-dd HH:mm:ss} %-5level %logger{36} - %msg%n</pattern> </encoder> </appender> <root level="INFO"> <appender-ref ref="FILE" /> </root> </configuration>
This configuration means that when the log file reaches 10MB, the system will generate a new log file and retain the old log file.
4. Application examples in e-commerce trading system
In the e-commerce transaction system, logging can help us track the execution of important operations such as order processing process, payment status, inventory updates, etc. Suppose we have an order service that handles the creation and update of orders. In these critical steps, we need to record the beginning, end of the operation, and possible errors.
4.1 Implement log printing for specified classes
In actual development, we may only want to log certain key classes or packages to avoid generating a large number of unrelated logs, which affects debugging efficiency. Spring Boot's log configuration allows you to set different log levels for specific classes or packages.
Example: We hope toAll class settings under the package
DEBUG
Level logs to record the order processing process in detail.
exist, you can configure it like this:
# Set DEBUG log level for the specified package=DEBUG
Or inmiddle:
logging: level: : DEBUG
This configuration method is very flexible and is suitable for scenarios where we only want to debug specific modules. For the order processing module in the e-commerce system, we can enable detailed logs for it in this way.
4.2 Implement the specified class to not print logs
If we want to ignore the log output of certain classes or packages, such as not wanting to record logs of certain third-party libraries, we can set its log level toOFF
. For example, if we don't wantThe class under the package outputs any logs, which can be configured like this:
# Disable log output of specified packages=OFF
existThis can also be achieved in this way:
logging: level: : OFF
This configuration method is usually suitable for classes or packages whose logs are redundant and do not affect the system's operation, and can effectively reduce the amount of logs.
4.3 Print the SQL log of MyBatis
In e-commerce systems, business scenarios such as order processing and inventory updates often involve database operations, and recording SQL logs is crucial to debug these operations. Spring Boot integrates MyBatis, which enables SQL log output easily through configuration.
To enable SQL logging for MyBatis, justor
The log component in MyBatis (usually
) Set log level:
# Enable SQL logs for MyBatis=DEBUG =DEBUG
Or inmiddle:
logging: level: : DEBUG : DEBUG
This will output all executed SQL statements and their parameters in the log, which is very useful for us to view the database interaction process when debugging.
4.4 Close the SQL log of MyBatis
If we do not want to print SQL logs of MyBatis (for example, in production environments, in order to reduce the amount of logs), we can set its log level toOFF
:
# Close the SQL logs of MyBatis=OFF =OFF
or:
logging: level: : OFF : OFF
In this way, we can flexibly adjust log output according to environmental needs. Turn on SQL logs in the development environment and shut down in the production environment, which can effectively reduce unnecessary log information.
4.5 Complete example of e-commerce transaction system log configuration
Here is a complete log configuration example that shows how to enable/disable logs for a specific class, how to print SQL logs for MyBatis, and turn off log output:
# The global log level is INFO=INFO # Enable DEBUG level log for order service=DEBUG # Prohibit log output of payment services=OFF # Enable SQL logs for MyBatis=DEBUG =DEBUG
This configuration can effectively manage log output in the e-commerce system, helping developers concentrate on debugging core business modules while avoiding log redundancy.
4.6 Record log case demonstration
import org.; import org.; import .*; @RestController @RequestMapping("/orders") public class OrderController { private static final Logger logger = (); @PostMapping("/create") public String createOrder(@RequestBody Order order) { ("Creating order with ID: {}", ()); // Simulate order processing logic try { // Order processing is successful ("Order created successfully: {}", ()); return "Order created"; } catch (Exception e) { // Order processing failed ("Failed to create order: {}", (), e); return "Order creation failed"; } } }
In this example, we used SLF4J'sLogger
To record the order creation process. Logs of information level in key steps (INFO
), while logs of error level are logged when an exception occurs (ERROR
)。
5. Common log problems and solutions
5.1 Problem 1: The log file is too large
Problem description: Log files grow infinitely and eventually fill up disk.
Solution: Configure log scrolling policy to limit the size of a single log file. Refer to the aboveThe configuration can be set
maxFileSize
To limit the size of the log file.
5.2 Problem 2: Improper log level configuration
Problem description: The log level is incorrectly set, resulting in excessive debugging information output in the development environment, affecting debugging efficiency, or lacking necessary log information in the production environment.
Solution: Use different log levels in development and production environments. Can be inDEBUG level log is configured, and in
INFO level log is configured.
# logging: level: root: DEBUG # logging: level: root: INFO
5.3 Problem 3: Multithreaded log printing is incomplete
Problem description: In a multi-threaded environment, the log content may be disrupted by concurrent threads, resulting in incomplete logs.
Solution: You can use Logback's asynchronous logging function to buffer concurrent output through asynchronous logs. Add the following configuration tomiddle:
<configuration> <appender name="ASYNC_FILE" class=""> <appender-ref ref="FILE" /> </appender> <root level="INFO"> <appender-ref ref="ASYNC_FILE" /> </root> </configuration>
Summarize
This is all about this article about Spring Boot log printing configuration. For more related Spring Boot log printing configuration content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!