introduction
In development, logging is an important means to ensure the robustness and maintainability of applications. Through logs, we can record the running status of the system, catch exceptions and debug.
Integrate logging in Spring Boot projects, common logging frameworks such as Logback or Log4j2 can be used.
Spring Boot uses Logback by default, but you can also choose other frameworks according to your needs. Here are several commonly used log integration methods:
1. Use Spring Boot's default Logback logging framework
Spring Boot has built-in Logback and provides default logging configuration. Just inor
Just make simple configuration.
step:
Introduce dependencies
If it is a standard Spring Boot project, there is usually no need to add additional dependencies, and Logback is already integrated. If you need a custom log framework, you canManually introduce dependencies:
<!-- logback-classicAlready included inspring-boot-startermiddle --> <dependency> <groupId></groupId> <artifactId>spring-boot-starter-logging</artifactId> </dependency>
Basic configuration
Can be inBasic log configuration:
#Console log output level=INFO =DEBUG # Customize the log level of a package# Log file output=logs/ =logs # Specify the path to the log storage=%d{yyyy-MM-dd HH:mm:ss} - %msg%n #Console log output format=%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n # File log output format
Log format adjustment
Can be used through LogbackThe file is configured in more detail. Create
src/main/resources/
The file, the content is as follows:
<configuration> <appender name="console" class=""> <encoder> <pattern>%d{yyyy-MM-dd HH:mm:ss} %-5level [%thread] %logger{36} - %msg%n</pattern> </encoder> </appender> <appender name="file" class=""> <file>logs/</file> <encoder> <pattern>%d{yyyy-MM-dd HH:mm:ss} %-5level [%thread] %logger{36} - %msg%n</pattern> </encoder> </appender> <root level="INFO"> <appender-ref ref="console" /> <appender-ref ref="file" /> </root> </configuration>
2. Use Log4j2 Log Framework
If you prefer Log4j2, you can integrate through the following steps.
step:
Introduce dependencies
existAdd the Log4j2 dependency to it and exclude the default Logback:
<dependency> <groupId></groupId> <artifactId>spring-boot-starter-log4j2</artifactId> </dependency>
Configure Log4j2
existsrc/main/resources
Created in the directoryThe file, the content is as follows:
<Configuration status="WARN"> <Appenders> <Console name="Console" target="SYSTEM_OUT"> <PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss} [%t] %-5level %logger{36} - %msg%n"/> </Console> <File name="File" fileName="logs/"> <PatternLayout> <pattern>%d{yyyy-MM-dd HH:mm:ss} [%t] %-5level %logger{36} - %msg%n</pattern> </PatternLayout> </File> </Appenders> <Loggers> <Root level="info"> <AppenderRef ref="Console"/> <AppenderRef ref="File"/> </Root> <Logger name="" level="debug" additivity="false"> <AppenderRef ref="Console"/> <AppenderRef ref="File"/> </Logger> </Loggers> </Configuration>
3. Use logs in code
Whether you use Logback or Log4j2, Spring Boot will inject it into youSLF4J
Interface. Use in your codeLoggerFactory
To record the log:
import org.; import org.; import ; import ; @RestController public class ExampleController { private static final Logger logger = (); @GetMapping("/example") public String example() { ("This is an info message"); ("This is a debug message"); ("This is an error message"); return "Logging example!"; } }
4. Use .slf4j.Slf4j
@Slf4j is an annotation provided by Lombok to simplify the process of logging. It will automatically inject a log object of type org. into the class, allowing you to manually create a Logger instance. @Slf4j is based on SLF4J (Simple Logging Facade for Java), which is a commonly used log framework interface that can be used in combination with a variety of log implementations (such as Logback, Log4j2, etc.).
1. Basic use
Add to class@Slf4j
Annotation, Lombok will automatically generate a name called “log
ofLogger
Example.
import .slf4j.Slf4j; @Slf4j public class ExampleService { public void doSomething() { ("This is an info message"); ("This is a debug message"); ("This is an error message"); } }
2. Log level
use@Slf4j
After annotation, you can use different levels of logging methods provided by SLF4J in your code, such as:
()
- Tracking logs for very detailed logging()
- Debug log()
- Information log()
- Warning log()
- Error log
3. Cooperate with Spring Boot and log configuration
In Spring Boot project, the Logback log framework is used by default, so you can use it directly without additional configuration.@Slf4j
Do log records.
Log level and format configurations can be used inor
Make adjustments in .
4. Sample code
import .slf4j.Slf4j; import ; @Slf4j @Service public class UserService { public void createUser(String username) { ("Creating user with name: {}", username); try { // Simulate some business logic ("Processing user creation logic..."); // If an error occurs if (username == null) { throw new IllegalArgumentException("Username cannot be null"); } } catch (Exception e) { ("Error creating user: {}", username, e); } } }
This is the end of this article about the four ways to integrate logs in SpringBoot. For more related SpringBoot integration log content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!