1. Introduction to SLF4J
SLF4J (Simple Logging Facade for Java) is a simple log facade that allows different log implementations (such as Logback, Log4j, etc.) to be selected at runtime. Through SLF4J, we can flexibly switch the log framework without modifying the code.
2. Add dependencies
Add SLF4J and Logback dependencies to the file:
<dependencies> <!-- SLF4J API --> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>2.0.9</version> </dependency> <!-- Logback Classic accomplish --> <dependency> <groupId></groupId> <artifactId>logback-classic</artifactId> <version>1.4.11</version> </dependency> </dependencies>
3. Configure Logback
Create a file in the src/main/resources directory and configure the log output format and level:
<configuration> <appender name="CONSOLE" class=""> <encoder> <pattern>%date %level [%thread] %logger{36} - %msg%n</pattern> </encoder> </appender> <appender name="FILE" class=""> <file>logs/</file> <encoder> <pattern>%date %level [%thread] %logger{36} - %msg%n</pattern> </encoder> </appender> <root level="info"> <appender-ref ref="CONSOLE" /> <appender-ref ref="FILE" /> </root> </configuration>
4. Record logs of different levels
(I) Get Logger instance
In Java class, get the Logger instance through LoggerFactory:
import org.; import org.; public class LoggingExample { private static final Logger logger = (); }
(II) Record logs of different levels
SLF4J supports multiple log levels, including trace, debug, info, warning and error. Depending on the different scenarios, you can choose the appropriate log level:
public class LoggingExample { private static final Logger logger = (); public static void main(String[] args) { // Record trace level logs ("This is a trace-level log"); // Record debug level logs ("This is a debug level log"); // Record info-level logs ("This is an info-level log"); // Record the log at the warning level ("This is a warning level log"); // Log error-level logs ("This is an error-level log"); } }
(III) Operation results
After running the above code, the console will output the following:
2024-11-28 10:00:00 INFO [main] LoggingExample - This is an info-level log
2024-11-28 10:00:00 WARN [main] LoggingExample - This is a warning level log
2024-11-28 10:00:00 ERROR [main] LoggingExample - This is an error-level log
At the same time, the log content will also be written to the logs/file.
5. Summary
With SLF4J and Logback, we can easily record logs at different levels in Java. SLF4J provides a unified log facade, and Logback, as a high-performance log implementation, can meet the needs of most application scenarios.
This is the end of this article about Java's examples of using SLF4J to record logs of different levels. For more related Java SLF4J log content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!