[Java] Exception handling using SLF4J and Logback

Using SLF4J and Logback

I introduced Commons Loggingand Log4jthis pair of good friends. One of them is responsible for serving as the log API, and the other is responsible for implementing the bottom layer of the log. It is very easy to develop when used together.

Some children's shoes may have heard of SLF4Jand Logback. These two things also look like logs, what are they?

In fact , SLF4Jsimilar 于Commons Loggingis also a log interface, and Logbacksimilar Log4jis a log implementation.

Why is there Commons Logginga harmony , and Log4jit pops up again ? This is because Java has a very long history of open source. Not only is it open source itself, but almost all the third-party libraries we use are open source. A feature of the rich open source ecosystem is that for the same function, several competing open source libraries can be found.SLF4JLogbackOpenJDK

Because the right Commons Logginginterface is not satisfied, someone did it SLF4J. Because of Log4jdissatisfaction with the performance of the device, someone did it Logback.

Let's first take a look at the improvements SLF4Jto the interface. Commons LoggingIn Commons Logging, we want to print the log, sometimes we have to write like this:

int score = 99;
p.setScore(score);
log.info("Set score " + score + " for Person " + p.getName() + " ok.");

Spelling strings is a very troublesome thing, so the log interface of SLF4J has been improved like this:

int score = 99;
p.setScore(score);
logger.info("Set score {} for Person {} ok.", score, p.getName());

We can also guess by guessing, SLF4Jthe log interface of the input is a string with placeholders, and the placeholders are automatically replaced with the following variables, so it looks more natural.

How to use it SLF4J? Its interface is virtually Commons Loggingidentical to:

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

class Main {
    
    
    final Logger logger = LoggerFactory.getLogger(getClass());
}

Compare the interface Commons Loggingwith and SLF4J:

Commons Logging	SLF4J
org.apache.commons.logging.Log	org.slf4j.Logger
org.apache.commons.logging.LogFactory	org.slf4j.LoggerFactory

The difference is that Logit becomes Logger, LogFactorybecomes LoggerFactory.

Using SLF4Jand L is similar to using plus ogbackmentioned above , first download and , and then put the following jar packages in the classpath:Commons LoggingLog4jSLF4JLogback

slf4j-api-1.7.x.jar
logback-classic-1.2.x.jar
logback-core-1.2.x.jar

Then use SLF4J's Logger and LoggerFactory. Similar to Log4j, we still need a Logback configuration file, put logback.xml in the classpath, and configure it as follows:

<?xml version="1.0" encoding="UTF-8"?>
<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.rolling.RollingFileAppender">
		<encoder>
			<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
			<charset>utf-8</charset>
		</encoder>
		<file>log/output.log</file>
		<rollingPolicy class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy">
			<fileNamePattern>log/output.log.%i</fileNamePattern>
		</rollingPolicy>
		<triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
			<MaxFileSize>1MB</MaxFileSize>
		</triggeringPolicy>
	</appender>

	<root level="INFO">
		<appender-ref ref="CONSOLE" />
		<appender-ref ref="FILE" />
	</root>
</configuration>

Run it to get output similar to the following:

13:15:25.328 [main] INFO  com.itranswarp.learnjava.Main - Start process...

Judging from the current trend, more and more open source projects have shifted from Commons Logging plus Log4j to SLF4J plus Logback.

summary

SLF4J and Logbackcan replace Commons Loggingand Log4j;

The interface that is always used SLF4Jis used to write logs. It Logbackonly needs to be configured and does not need to modify the code.

おすすめ

転載: blog.csdn.net/ihero/article/details/132202424