Java SLF4J下载引用配置使用方法

本文主要介绍Java中,日志框架SLF4J下载引用配置的方法,以及使用的相关示例代码。

1、SLF4J引用

1) 手动引用

下载地址https://github.com/qos-ch/slf4j/releases

2) 使用Maven配置依赖

Maven中pom.xml添加如下:

<dependency> 
<groupId>org.slf4j</groupId>
<artifactId>slf4j-jdk14</artifactId>
<version>1.7.28</version>
</dependency>

2、使用示例代码

1) 简单记录代码

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class HelloWorld {
public static void main(String[] args) {
Logger logger = LoggerFactory.getLogger(HelloWorld.class);
logger.info("Hello World");
}
}

2) 典型用法代码

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Wombat {
final Logger logger = LoggerFactory.getLogger(Wombat.class);
Integer t;
Integer oldT;
public void setTemperature(Integer temperature) {
oldT = t;
t = temperature;
logger.debug("Temperature set to {}. Old temperature was {}.", t, oldT);
if(temperature.intValue() > 50) {
logger.info("Temperature has risen above 50 degrees.");
}
}
}

3) 简洁的API

logger.atInfo().log("Hello world");

等同于

logger.info("Hello world.");

记录debug日志:

int newT = 15;
int oldT = 16;
// using traditional API
logger.debug("Temperature set to {}. Old temperature was {}.", newT, oldT);
// using fluent API, add arguments one by one and then log message
logger.atDebug().addArgument(newT).addArgument(oldT).log("Temperature set to {}. Old temperature was {}.");
// using fluent API, log message with arguments
logger.atDebug().log("Temperature set to {}. Old temperature was {}.", newT, oldT);
// using fluent API, add one argument and then log message providing one more argument
logger.atDebug().addArgument(newT).log("Temperature set to {}. Old temperature was {}.", oldT);
// using fluent API, add one argument with a Supplier and then log message with one more argument.
// Assume the method t16() returns 16.
logger.atDebug().addArgument(() -> t16()).log(msg, "Temperature set to {}. Old temperature was {}.", oldT);

等价于:

int newT = 15;
int oldT = 16;
// using classical API
logger.debug("oldT={} newT={} Temperature changed.", newT, oldT);
// using fluent API
logger.atDebug().addKeyValue("oldT", oldT).addKeyValue("newT", newT).log("Temperature changed.");   

相关文档:

http://www.slf4j.org/manual.html

https://github.com/qos-ch/slf4j

推荐阅读
cjavapy编程之路首页