How Java uses Logback to record logs
Logback is a Java based logging framework, an improved version of log4j, and a native implementation of SLF4J. It has three core components: Logger, Appender, and Layout.
1. Logger: Logger is the main component of the Logback logging system, used to record log information. The Logger allows you to choose which log level information to record and which Appender to send the log information to for processing.
2. Appender: Appender is used to process the log information sent by the Logger. Logback provides various appenders, including ConsoleAppender (output to console), FileAppender (output to file), RollingFileAppender (support for scrolling of log files), and so on.
3. Layout: Layout is used to format the log information sent by the Logger and provides multiple formatting options by default.
Common methods:
1. Use Logger to record log information:
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class MyLogger {
private static final Logger LOGGER = LoggerFactory.getLogger(MyLogger.class);
public static void main(String[] args) {
LOGGER.debug("Debug message");
LOGGER.info("Info message");
LOGGER.warn("Warn message");
LOGGER.error("Error message");
}
}
2. Configure Logback.xml:
Create a logback.xml file in the src/main/resources directory and define the behavior of the Logger through the configuration file.
<configuration>
<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
</encoder>
</appender>
<appender name="FILE" class="ch.qos.logback.core.FileAppender">
<file>myapp.log</file>
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
</encoder>
</appender>
<logger name="com.example" level="debug"/>
<root level="info">
<appender-ref ref="CONSOLE"/>
<appender-ref ref="FILE"/>
</root>
</configuration>
Maven Dependency:
Add the following dependencies to the pom.xml file:
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.2.3</version>
</dependency>
The above is a brief introduction and usage method of Logback, which can be configured and used according to actual needs.