文档章节

slf4j查看

dxbj1010
 dxbj1010
发布于 2015/10/10 10:20
字数 517
阅读 41
收藏 0

###slf4j查看

  1. 先从LoggerFactory这个类入手,起始于getLogger方法

    public static Logger getLogger(String name) {
    	ILoggerFactory iLoggerFactory = getILoggerFactory();
    	return iLoggerFactory.getLogger(name);
    }
    

getILoggerFactory调用后找寻的是类路中StaticLoggerBinder的实现类。

	private final static void bind() {
	    try {
	      Set staticLoggerBinderPathSet = findPossibleStaticLoggerBinderPathSet();
	      reportMultipleBindingAmbiguity(staticLoggerBinderPathSet);
	      // the next line does the binding
	      StaticLoggerBinder.getSingleton();
	      INITIALIZATION_STATE = SUCCESSFUL_INITIALIZATION;
	      reportActualBinding(staticLoggerBinderPathSet);
	      emitSubstituteLoggerWarning();
	    } catch (NoClassDefFoundError ncde) {
	      String msg = ncde.getMessage();
	      if (messageContainsOrgSlf4jImplStaticLoggerBinder(msg)) {
	        INITIALIZATION_STATE = NOP_FALLBACK_INITIALIZATION;
	        Util.report("Failed to load class \"org.slf4j.impl.StaticLoggerBinder\".");
	        Util.report("Defaulting to no-operation (NOP) logger implementation");
	        Util.report("See " + NO_STATICLOGGERBINDER_URL
	                + " for further details.");
	      } else {
	        failedBinding(ncde);
	        throw ncde;
	      }
	    } catch (java.lang.NoSuchMethodError nsme) {
	      String msg = nsme.getMessage();
	      if (msg != null && msg.indexOf("org.slf4j.impl.StaticLoggerBinder.getSingleton()") != -1) {
	        INITIALIZATION_STATE = FAILED_INITIALIZATION;
	        Util.report("slf4j-api 1.6.x (or later) is incompatible with this binding.");
	        Util.report("Your binding is version 1.5.5 or earlier.");
	        Util.report("Upgrade your binding to version 1.6.x.");
	      }
	      throw nsme;
	    } catch (Exception e) {
	      failedBinding(e);
	      throw new IllegalStateException("Unexpected initialization failure", e);
	    }
	  }

进入到findPossibleStaticLoggerBinderPathSet方法:

	private static Set findPossibleStaticLoggerBinderPathSet() {
	    // use Set instead of list in order to deal with  bug #138
	    // LinkedHashSet appropriate here because it preserves insertion order during iteration
	    Set staticLoggerBinderPathSet = new LinkedHashSet();
	    try {
	      ClassLoader loggerFactoryClassLoader = LoggerFactory.class
	              .getClassLoader();
	      Enumeration paths;
	      if (loggerFactoryClassLoader == null) {
	        paths = ClassLoader.getSystemResources(STATIC_LOGGER_BINDER_PATH);
	      } else {
	        paths = loggerFactoryClassLoader
	                .getResources(STATIC_LOGGER_BINDER_PATH);
	      }
	      while (paths.hasMoreElements()) {
	        URL path = (URL) paths.nextElement();
	        staticLoggerBinderPathSet.add(path);
	      }
	    } catch (IOException ioe) {
	      Util.report("Error getting resources from path", ioe);
	    }
	    return staticLoggerBinderPathSet;
	  }

通过classLoader加载的类是org/slf4j/impl/StaticLoggerBinder.class是否在类路径存在。如果有多个会或者0个会提示报错信息。

最后间接使用的loggerFactory是Log4jLoggerFactory

private StaticLoggerBinder() {
    loggerFactory = new Log4jLoggerFactory();
    try {
        @SuppressWarnings("unused")
        Level level = Level.TRACE;
    } catch (NoSuchFieldError nsfe) {
        Util.report("This version of SLF4J requires log4j version 1.2.12 or later. See also http://www.slf4j.org/codes.html#log4j_version");
    }
}

通过getLogger方法得到是log4j jar包里面的org.apache.log4j.Logger log4jLogger

public Logger getLogger(String name) {
    Logger slf4jLogger = loggerMap.get(name);
    if (slf4jLogger != null) {
        return slf4jLogger;
    } else {
        org.apache.log4j.Logger log4jLogger;
        if (name.equalsIgnoreCase(Logger.ROOT_LOGGER_NAME))
            log4jLogger = LogManager.getRootLogger();
        else
            log4jLogger = LogManager.getLogger(name);

        Logger newInstance = new Log4jLoggerAdapter(log4jLogger);
        Logger oldInstance = loggerMap.putIfAbsent(name, newInstance);
        return oldInstance == null ? newInstance : oldInstance;
    }
}

ConcurrentMap会多一个方法putIfAbsent相对于普通map。不存在的时候插入,存在的时候不改变。--相对也是线程安全的。

logger返回时候 还是要包装一下成org.slf4j.Logger接口,方便通用。

public void debug(String format, Object arg) {
    if (logger.isDebugEnabled()) {
        FormattingTuple ft = MessageFormatter.format(format, arg);
        logger.log(FQCN, Level.DEBUG, ft.getMessage(), ft.getThrowable());
    }
}

举出其中一个的例子,logger.isDebugEnabled代替了以前代码里面很繁琐的判断过程。使用装饰器对log4j的logger进行了加强。还支持message占位符支持。也算是一个不错的优点了。

© 著作权归作者所有

共有 人打赏支持
dxbj1010
粉丝 5
博文 12
码字总数 7474
作品 0
武汉
程序员
私信 提问
SLF4J: Multiple bindings were found on the class path

众所周知,SLF4J是一个日志门面框架,它的作用是用于定义统一的日志接口,而具体的日志实现是由各个日志框架实现的,比如log4j,logback等。 问题 在使用SLF4J时,当class path同时包含了多个...

勇敢的飞石
05/17
0
0
用自带的jetty启动后,出现Class path contains multiple SLF4J bindings.

@李小热 你好,想跟你请教个问题: 用自带的jetty启动后,出现如下错误,将这三个冲突的包,逐个替换删除,还是不能解决。新手,望给予解答。 Starting JFinal 1.5 SLF4J: Class path contai...

雨夜23
2013/12/24
2.8K
3
执行hive命令,卡住了,看日志,没啥信息,咋搞

[hadoop@master ~]$ hive SLF4J: Class path contains multiple SLF4J bindings. SLF4J: Found binding in [jar:file:/bigdata/hadoop/share/hadoop/common/lib/slf4j-log4j12-1.7.5.jar!/or......

知行合一1
2016/03/17
2.4K
2
SLF4J: The requested version 1.5.8 by your slf4j

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

测试-雨
2015/01/15
0
0
ActiveMQ 功能

activemq-all-5.8.0.jar,和slf4j-log4j12-1.6.1.jar 冲突了,这个怎么解决呢。 SLF4J: Class path contains multiple SLF4J bindings. SLF4J: Found binding in [jar:file:/C:/Users/chen/.......

唯风
2014/01/15
967
2

没有更多内容

加载失败,请刷新页面

加载更多

day179-2018-12-16-英语流利阅读-待学习

《海王》:上映 7 天,票房突破 9 亿,DC 要翻身? Daniel 2018-12-16 1.今日导读 这部电影堪称“有《阿凡达》般的视觉奇观,《指环王》般的史诗质感,《夺宝奇兵》般的寻宝历险,《狮子王》...

飞鱼说编程
15分钟前
5
0
window下安装maven

1.下载软件包: 2.解压到当前的安装路径: D:\Maven3.5.3 3.添加环境变量: 新建一个名为:MAVEN_HOME 填写解压路径:D:\Maven3.5.3 打开path,添加:%MAVEN_HOME%\bin 确定即可。 4.验证环境...

狼王黄师傅
29分钟前
5
0
聊聊flink的FsCheckpointStorage

序 本文主要研究一下flink的FsCheckpointStorage CheckpointStorage flink-runtime_2.11-1.7.0-sources.jar!/org/apache/flink/runtime/state/CheckpointStorage.java /** * CheckpointStor......

go4it
51分钟前
3
0
makefile 常用函数

Linux 环境下的程序员如果不会使用GNU make来构建和管理自己的工程,应该不能算是一个合格的专业程序员,至少不能称得上是 Unix程序员。今天我们来学习下makefile的常用函数。 《GNU make》h...

科陆李明
今天
21
0
Android 报错 Could not find com.android.tools.build:aapt2:3.2.1-4818971.

报错信息: Could not find com.android.tools.build:aapt2:3.2.1-4818971.Searched in the following locations: file:/C:/Users/96110/AppData/Local/Android/Sdk/extras/m2reposito......

lanyu96
今天
10
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部