SLF4J 簡介

来源:互联网 发布:windows tasksche.exe 编辑:程序博客网 时间:2024/06/05 19:33

SLF4J即 Simple Logging Facade for Java,是對各種log框架的抽象。

版本變化

1.6.0

如果沒有與特定的log框架綁定,則SLF4J默認爲一個無操作的實現。

1.7.0

logger接口中的打印方法提供了可變參數varargs(從JDK5開始支持),替代了Object[]。

即由

Object[] arguments = {    new Integer(7),    new Date(),    "a disturbance in the Force"};String result = MessageFormat.format(    "At {1,time} on {1,date}, there was {2} on planet "     + "{0,number,integer}.", arguments);

簡化爲

String result = MessageFormat.format(    "At {1,time} on {1,date}, there was {2} on planet "    + "{0,number,integer}.",    7, new Date(), "a disturbance in the Force");

1.7.5

Significant improvement in logger retrieval times.

1.7.9

By setting theslf4j.detectLoggerNameMismatchsystem property to true, SLF4J can automatically spot incorrectly named loggers.

Hello World

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");  }}
只添加slf4j-api-1.7.13.jar會出現警告:

SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".SLF4J: Defaulting to no-operation (NOP) logger implementationSLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.

因爲此時SLF4J還未綁定,最簡單的情況可以添加slf4j-simple-1.7.13.jar,得到正確輸出

0 [main] INFO HelloWorld - Hello World

Typical usage pattern

注意佔位符{}的使用

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.");    }   }} 

綁定特定的log框架



logback-classic-1.0.13.jar (requires logback-core-1.0.13.jar)
NATIVE IMPLEMENTATION There are also SLF4J bindings external to the SLF4J project, e.g. logback which implements SLF4J natively. Logback's ch.qos.logback.classic.Logger class is a direct implementation of SLF4J's org.slf4j.Logger interface. Thus, using SLF4J in conjunction with logback involves strictly zero memory and computational overhead.


maven中的設置

<dependency>   <groupId>ch.qos.logback</groupId>  <artifactId>logback-classic</artifactId>  <version>1.0.13</version></dependency>

兼容性

slf4j-api的所有版本都是互相兼容的(也就是說版本的變遷,不用改變code),需要考慮的只是綁定版本是否與slf4j-api兼容,如slf4j-api-1.7.13應該使用 slf4j-simple-1.7.13,使用slf4j-simple-1.5.5就會出現問題。

通過SLF4J統一logging

please refer to the page onBridging legacy APIs.


MDC

目前只有log4j和logback支持MDC,如果使用不支持MDC的框架,SLF4J仍將存儲MDC數據,但用戶需要手動取回數據。

For more information on MDC please see thechapter on MDC in the logback manual.

0 0
原创粉丝点击