首页 > 其他分享 >LogFacade---SLF4J

LogFacade---SLF4J

时间:2023-11-29 18:33:46浏览次数:27  
标签:StaticLoggerBinder INITIALIZATION SLF4J --- getLogger slf4j LogFacade org Logger

概述

Simple Logging Facade for Java(SLF4J);

用作各种日志框架(eg:java.util.logging,logback,log4j)的简单外观或抽象,允许最终用户在部署 时插入所需的日志记录框架;

 

不提供完整的日志记录解决方案;

使用SLF4J无法执行配置appender或设置日志记录级别等操作。

因此,在某个时间点,任何非平凡的应用程序都需要直接调用底层日志记录系统;

因此一般情况下slf4j都会和log4j,logback等日志框架一起使用;

 

slf4j是一个日志标准,同时日志框架都会实现这个标准,因此使用slf4j可以极大的降低维护成本;

 

链路

LoggerFactory.getLogger

// org.slf4j.LoggerFactory.getLogger(java.lang.Class)
    // Return a logger named corresponding to the class passed as parameter, using the statically bound {@link ILoggerFactory} instance.
    public static Logger getLogger(Class clazz) {
        return getLogger(clazz.getName());
    }

    // org.slf4j.LoggerFactory.getLogger(java.lang.String)
    // Return a logger named according to the name parameter using the statically bound {@link ILoggerFactory} instance.
    public static Logger getLogger(String name) {
        ILoggerFactory iLoggerFactory = getILoggerFactory();
        return iLoggerFactory.getLogger(name);
    }

    // org.slf4j.LoggerFactory.getILoggerFactory
    // Return the {@link ILoggerFactory} instance in use.ILoggerFactory instance is bound with this class at compile time.
    public static ILoggerFactory getILoggerFactory() {
        if (INITIALIZATION_STATE == UNINITIALIZED) {
            INITIALIZATION_STATE = ONGOING_INITIALIZATION;
            performInitialization();
        }
        switch (INITIALIZATION_STATE) {
            case SUCCESSFUL_INITIALIZATION:
                return StaticLoggerBinder.getSingleton().getLoggerFactory();
            case NOP_FALLBACK_INITIALIZATION:
                return NOP_FALLBACK_FACTORY;
            case FAILED_INITIALIZATION:
                throw new IllegalStateException(UNSUCCESSFUL_INIT_MSG);
            case ONGOING_INITIALIZATION:
                // support re-entrant behavior.
                // See also http://bugzilla.slf4j.org/show_bug.cgi?id=106
                return TEMP_FACTORY;
        }
        throw new IllegalStateException("Unreachable code");
    }

    // org.slf4j.LoggerFactory.performInitialization
    private final static void performInitialization() {
        bind();
        if (INITIALIZATION_STATE == SUCCESSFUL_INITIALIZATION) {
            versionSanityCheck();
        }
    }

    // org.slf4j.LoggerFactory.bind
    private final static void bind() {
        try {
            Set staticLoggerBinderPathSet = findPossibleStaticLoggerBinderPathSet();  // 获取classpath下的org/slf4j/impl/StaticLoggerBinder.class
            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);
        }
    }

    // org.slf4j.LoggerFactory.findPossibleStaticLoggerBinderPathSet
    // We need to use the name of the StaticLoggerBinder class, but we can't reference the class itself.
    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);   // 获取classpath下的org/slf4j/impl/StaticLoggerBinder.class
            }
            while (paths.hasMoreElements()) {
                URL path = (URL) paths.nextElement();
                staticLoggerBinderPathSet.add(path);
            }
        } catch (IOException ioe) {
            Util.report("Error getting resources from path", ioe);
        }
        return staticLoggerBinderPathSet;
    }

    // org.slf4j.impl.StaticLoggerBinder.getSingleton
    public static StaticLoggerBinder getSingleton() {
        return SINGLETON;
    }

    // ch.qos.logback.classic.LoggerContext.getLogger(java.lang.String)
    public final Logger getLogger(final String name) {
        //...
        Logger childLogger = (Logger) loggerCache.get(name);       // 从缓存中取对应name的Logger  
        //...
        loggerCache.put(childName, childLogger);
    }

  

log.debug

由具体的 log 实现;

 

标签:StaticLoggerBinder,INITIALIZATION,SLF4J,---,getLogger,slf4j,LogFacade,org,Logger
From: https://www.cnblogs.com/anpeiyong/p/17865571.html

相关文章

  • DCR-2855路由器升级
    #命令介绍:利用copy命令使用copy命令可以从TFTP服务器读取文件到路由器flash闪存,也可以将路由器flash闪存中的某个文件写到TFTP服务器。或者从CF卡读取文件到路由器flash闪存或TFTP服务器,也可将TFTP服务器或路由器flash闪存中的某个文件写到CF卡。或者从......
  • [LettCode-中等] 字母异位词分组
    这是一道中等难度题,首先我们来了解一下,什么是字母异位词 =》由重新排列源单词的所有字母得到一个新单词字母异位词=》它是这个意思,比如说一个字符串由3个字符abc组成,就是"abc",现在我把组成这个字符串的字母顺序随意调换,比如变成"bac","bca","cab"等,这几个词就是字母异位......
  • Jenkins +miniprogram-ci 构建 发布、预览微信小程序
    #!/bin/bash-lsed-i"s/currentEnvironment='.*'/currentEnvironment='$DEPLOY_ENV'/g"'/var/lib/jenkins/workspace/nfc_recharge/utils/config.js'rm-rfqrcode*.jpgyarnyarnwxcitype=$actionappid=$appidversion......
  • shell脚本5---信号处理
    信号的类别信号值描述1SIGHUP挂起进程2SIGINT终止进程3SIGQUIT停止进程9SIGKILL无条件终止进程15SIGTERM优雅的终止进程17SIGSTOP无条件停止进程,但不是终止进程18SIGTSTP停止或暂停进程,但不是终止进程19SIGCONT继续运行停止的进......
  • 11.26-task5-条件
    条件if语句if(condition):后面为condition为trueelse:后面为false布尔表达式的使用:我们知道当布尔值为true是返回值为1,false时返回值为0他的返回值意思是:检查n是否为负数,若为负数n<0为true=1n>=0为false=0,+前面就为1*-n,+后就为0,为正数时逻辑相同ifelse推导式......
  • Android-ActivityResultAPI
    Android-ActivityResultAPI1.推出目的如果你将项目中的appcompat库升级到1.3.0或更高的版本,你会发现startActivityForResult()方法已经被废弃了。现在更加建议使用ActivityResultAPI来实现在两个Activity之间交换数据的功能。2.传统写法-在两个Activity之间交换数据如......
  • Ant-Design modal对话框未打开时,无法通过uesRef获取modal内部元素DOM节点
    为什么要记录下来呢?因为我在网上和chatGpt上没有搜到合适的解决方案。在CDNS上看到个和我遇到问题一样的,居然要收费才能看,所以自己记下来。当然肯定还有其他的好方案,欢迎大家留言。需求:使用antdV/g6画关系图,类似于企查查上面的那样:点击按钮打开Modal框,把数据渲染到Modal框的div......
  • 11.29-task5-代码风格
    代码风格代码风格介绍修饰代码的前提是代码没有bug。。。两幅图中的代码对比,显然后一幅图的代码更加简洁,易懂。也方便之后很长时间后的再理解。缩进tab==4个空格当函数有多参数时换行当一个语句的字符数过长,要换行运算符对齐导入规范导入时要遵循同级文......
  • Golang-常见数据结构实现原理
    chan 1.chan数据结构 src/runtime/chan.go:hchan定义了channel的数据结构:typehchanstruct{qcountuint//当前队列中剩余元素个数dataqsizuint//环形队列长度,即可以存放的元素个数bufunsafe.Pointer//环形队列指针......
  • JacksonUtils - 封装基于 jackson 的 json 转换逻辑代码
    JacksonUtils.javapackageorg.example.util;importcom.fasterxml.jackson.core.JsonProcessingException;importcom.fasterxml.jackson.databind.JavaType;importcom.fasterxml.jackson.databind.JsonNode;importcom.fasterxml.jackson.databind.ObjectMapper;im......