Logback源码分析系列之一起来看logback源码

一起来看logback源码(-)

已经工作4,5年了,经常使用各种日志框架,log4j,logback,logx,jul,jcl,log4j2等等,这些日至框架使用起来非常简单,易上手,但是自己实际上并没有对日志进行深入地分析和了解,
介于业界都评价logback日志系统做的精妙,基于学习的心理,来读读他的源码,预计花费一到两个月的时间,进行研究学习
那么读源码我们时,我们首先需要关注一下,他的入口

首先logback实现了slf4j,那么什么是slf4j呢?这里做一下简单的介绍,slf4j(simple logging facade for java) 他是一个简单的日志门面,并不是一个具体的日至解决方案,而logback就是他
的一个实现

logback版本:1.2.*
slf4j版本:1.7.25

其他版本的应该大同小异,但是slf4j1.8的去掉了用StaticLoggerBinder的方法

slf4j源码入口

说起logback的源码入口,咱们就需要从slf4j最关键的两个接口类说起,还有一个入口类,这3个类搞清楚,

首先最关键的两个接口,分别是Logger和ILoggerFactory. 最关键的入口类,是LoggerFactory

而所有具体实现框架,一定会实现Logger接口和ILoggerFactory接口,第一个实际记录日志,后者用来提供Logger,重要性不言自明.而LoggerFactory类,则是前面说过的入口类

 final static Logger logger = LoggerFactory.getLogger(MyApp1.class);

通过上面的代码,我们看出LoggerFactory.getLogger(),这个方法就是入口,那么咱们去看一下这个方法里到底都做了些什么

 public static Logger getLogger(Class<?> clazz) {
        Logger logger = getLogger(clazz.getName());
        if (DETECT_LOGGER_NAME_MISMATCH) {
            Class<?> autoComputedCallingClass = Util.getCallingClass();
            if (autoComputedCallingClass != null && nonMatchingClasses(clazz, autoComputedCallingClass)) {
                Util.report(String.format("Detected logger name mismatch. Given name: \"%s\"; computed name: \"%s\".", logger.getName(),
                                autoComputedCallingClass.getName()));
                Util.report("See " + LOGGER_NAME_MISMATCH_URL + " for an explanation");
            }
        }
        return logger;
    }

方法第一行调用了一个内部的getLogger()方法,那么这个方法里究竟做了什么呢?来让我们一步一步扒开伪装,看清他里面究竟是如何做的.上方法

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

这块代码中调用了另一个内部方法getLoggerFactory(),那么这个方法里面是做了什么呢,从方法名中看,这是一个工厂模式,工厂返回一个ILoggerFactory的实例,咱们接着往下看

    public static ILoggerFactory getILoggerFactory() {
        if (INITIALIZATION_STATE == UNINITIALIZED) {
            synchronized (LoggerFactory.class) {
                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://jira.qos.ch/browse/SLF4J-97
            return SUBST_FACTORY;
        }
        throw new IllegalStateException("Unreachable code");
    }

这段代码,第一部分检查初始化状态,如果是未初始化的情况,会有一个同步对象的方法,来处理初始化,
第二部分的代码就是处理不同状态返回值,如正常初始化成功,NOP初始化,初始化失败,正在初始化,其他状态都为失败

咱们先看一下未初始化这部分代码,首先这里用了double check, 未同步LoggerFactory对象时,判断一次初始化状态,同步后,判断一次状态,如果还是位初始化,则首先把初始化状态改为正在初始化状态,接下来就是关键的初始化代码了performInitialization(), 开始真正的执行初始化方法,咱们先来看看他初始化代码中都做了什么

    private final static void performInitialization() {
        bind();
        if (INITIALIZATION_STATE == SUCCESSFUL_INITIALIZATION) {
            versionSanityCheck();
        }
    }

这是一个方法用final修改是无法修改的,这个方法里很简单一个bind()方法,第二部对初始化成功后做的版本检查

那么咱们就先来看看bind()方法内部究竟是在做了什么

    private final static void bind() {
        try {
            Set<URL> staticLoggerBinderPathSet = null;
            // skip check under android, see also
            // http://jira.qos.ch/browse/SLF4J-328
            if (!isAndroid()) {
                staticLoggerBinderPathSet = findPossibleStaticLoggerBinderPathSet();
                reportMultipleBindingAmbiguity(staticLoggerBinderPathSet);
            }
            // the next line does the binding
            StaticLoggerBinder.getSingleton();
            INITIALIZATION_STATE = SUCCESSFUL_INITIALIZATION;
            reportActualBinding(staticLoggerBinderPathSet);
            fixSubstituteLoggers();
            replayEvents();
            // release all resources in SUBST_FACTORY
            SUBST_FACTORY.clear();
        } 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.contains("org.slf4j.impl.StaticLoggerBinder.getSingleton()")) {
                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);
        }
    }

代码分两部分 ,第一部分首先定义了一个静态绑定的集合,然后判断如果不是安卓的话,需要查找可能会有集合路径,然后报告可能存在多个绑定,但是多个绑定,

首先来看看slf4j是如何查找类路径下是由多个绑定的findPossibleStaticLoggerBinderPathSet这个方法
方法内容如下

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

首先这里用了另一个LinkedHashSet集合,为什么呢?我是这么想的,如果这里用了HashSet之类的,那么假如有多个Slf4j绑定实现在处理时,取第一个时候,就有可能不是按放入的顺序来处理了,OK,接下来这里获取加载LoggerFactory的ClassLoader,那么获取这个类加载去做什么呢?,下面的代码也很简单,直接判断获取loggerFactoryClassLoader是否为空,如果为空的话,用系统类加载器获取STATIC_LOGGER_BINDER_PATH ,通过查看定义发现STATIC_LOGGER_BINDER_PATH的值为”org/slf4j/impl/StaticLoggerBinder.class”, 那么getSystemResources是用来做什么的或者getResources, OK ,这个方法差不多看完了,就是把返回的多个类的绝对路径返回,那么咱们再往底层看,看getResources下面是怎么处理,怎么查找出类在那个jar包中,代码如下

ClassLoader.getResource(path) 从/下查找,path以/开头会返回null,会缓存结果
ClassLoader.getResources(path) 同上,返回多个
ClassLoader.getSystemResource(path) 不会缓存结果,每次都会重新加载

    public Enumeration<URL> getResources(String name) throws IOException {
        @SuppressWarnings("unchecked")
        Enumeration<URL>[] tmp = (Enumeration<URL>[]) new Enumeration<?>[2];
        if (parent != null) {
            tmp[0] = parent.getResources(name);
        } else {
            tmp[0] = getBootstrapResources(name);
        }
        tmp[1] = findResources(name);

        return new CompoundEnumeration<>(tmp);
    }

首先判断该类加载器是否有父加载器,如果有的话,就让父加载器处理,如果没有调用getBootstrapResources,

由于父类的类加载器还是该方法,那么我们直接来看getBootstrapResources()这个方法

    private static Enumeration<URL> getBootstrapResources(String name)
        throws IOException
    {
        final Enumeration<Resource> e =
            getBootstrapClassPath().getResources(name);
        return new Enumeration<URL> () {
            public URL nextElement() {
                return e.nextElement().getURL();
            }
            public boolean hasMoreElements() {
                return e.hasMoreElements();
            }
        };
    }

这个方法中就是获取getBootstrapClassPath()

我们来查看一下这个方法的实现

static URLClassPath getBootstrapClassPath() {
        return sun.misc.Launcher.getBootstrapClassPath();
    }

Ok,到这里,如果再往下面看就是Java的入口类,那么入口类实际上使用C写的,下面的代码就需要深入JVM源码,才能看到了,咱们只是为了一探slf4j那么我们就接着前面的内容,ClassLoader的内容就到此结束了,findPossibleStaticLoggerBinderPathSet,接着我们查找到的绑定实现类后,需要报告,那么看一下什么情况下会报多个绑定存在reportMultipleBindingAmbiguity()

    private static void reportMultipleBindingAmbiguity(Set<URL> binderPathSet) {
        if (isAmbiguousStaticLoggerBinderPathSet(binderPathSet)) {
            Util.report("Class path contains multiple SLF4J bindings.");
            for (URL path : binderPathSet) {
                Util.report("Found binding in [" + path + "]");
            }
            Util.report("See " + MULTIPLE_BINDINGS_URL + " for an explanation.");
        }
    }

首先判断是否存在多个绑定在类路径中,那么咱们看一下这个是如何判断的,这个判断也非常简单,只要集合的数量大于1即说明类路径下面存在多个slf4j的绑定实现

org.slf4j.LoggerFactory

    private static boolean isAmbiguousStaticLoggerBinderPathSet(Set<URL> binderPathSet) {
        return binderPathSet.size() > 1;
    }

如果是大于1,那么会打印一条警告信息,Util.report(),那么这个警告信息是如何处理的,咱们看一下这个静态的工具类

org.slf4j.helpers.Util


    static final public void report(String msg) {
        System.err.println("SLF4J: " + msg);
    }

Utils.report方法很简单,是静态方法,方法内部调用的是System.err.这个都是一目了然的,不解释

OK,到这里,slf4j,会把类路径下面可能有多个绑定通过ClassLoader,加载出来,然后如果有多个会警告,那么静下来需要做什么呢?咱们接着看bind()方法,接下来就是关键代码StaticLoggerBinder.getSingleton();

这个代码就是真正实现方法,那么咱们看一下该方法

logback-classic 中实现的//org.slf4j.impl.StaticLoggerBinder

 public static StaticLoggerBinder getSingleton() {
        return SINGLETON;
    }

这里直接返回了一个SINGLETON,那么这个SINGLETON是从哪里来的,通过查看它的定义,定义如下

private static StaticLoggerBinder SINGLETON = new StaticLoggerBinder();

是通过静态常量做的单利模式,在查看这个类里,发现这个类里有一个静态代码块

logback初始化配置

    static {
        SINGLETON.init();
    }

这里Logback做了一些初始化代码,咱们查看一下都初始化了什么

    void init() {
        try {
            try {
                new ContextInitializer(defaultLoggerContext).autoConfig();
            } catch (JoranException je) {
                Util.report("Failed to auto configure default logger context", je);
            }
            // logback-292
            if (!StatusUtil.contextHasStatusListener(defaultLoggerContext)) {
                StatusPrinter.printInCaseOfErrorsOrWarnings(defaultLoggerContext);
            }
            contextSelectorBinder.init(defaultLoggerContext, KEY);
            initialized = true;
        } catch (Exception t) { // see LOGBACK-1159
            Util.report("Failed to instantiate [" + LoggerContext.class.getName() + "]", t);
        }
    }

初始化上下文,并加载自动配置,那么先看一下上下文都初始化了什么new ContextInitializer(defaultLoggerContext),这里有一个defaultLoggerContext,
那么这个变量具体是什么值,咱们来看一下,刚看到这里的时候还有些小疑惑,怎么defaultLoggerContext是一个普通的成员变量,应该是静态代码块优先执行啊,
后来发现SINGLETON变量是静态变量,那么这个静态变量在static静态代码块前面,他优先执行,那么这个顺序就是SINGLETON->defaultLoggerContext->StaticLoggerBinder()->SINGLETON.init,

先看一下defaultLoggerContext的声明

    private LoggerContext defaultLoggerContext = new LoggerContext();

按顺寻来看一下StaticLoggerBinder()方法中做了什么

    private StaticLoggerBinder() {
        defaultLoggerContext.setName(CoreConstants.DEFAULT_CONTEXT_NAME);
    }

简单设置了默认上下文名称,那么这个名称又是什么呢?,通过追踪定义,在logbakc-core模块中发现定义的核心常量

public static final String DEFAULT_CONTEXT_NAME = "default";

原来只是把默认上下文的名称设置为default
new ContextInitializer(defaultLoggerContext),到此我们知道了,默认上下文是在这个地方设置的,

ch.qos.logback.classic.util.ContextInitializer

    public ContextInitializer(LoggerContext loggerContext) {
        this.loggerContext = loggerContext;
    }

然后我们再来看一下,这个new ContextInitializer(defaultLoggerContext).autoConfig();
autoConfig()方法都做了什么

    public void autoConfig() throws JoranException {
        StatusListenerConfigHelper.installIfAsked(loggerContext);
        URL url = findURLOfDefaultConfigurationFile(true);
        if (url != null) {
            configureByResource(url);
        } else {
            Configurator c = EnvUtil.loadFromServiceLoader(Configurator.class);
            if (c != null) {
                try {
                    c.setContext(loggerContext);
                    c.configure(loggerContext);
                } catch (Exception e) {
                    throw new LogbackException(String.format("Failed to initialize Configurator: %s using ServiceLoader", c != null ? c.getClass()
                                    .getCanonicalName() : "null"), e);
                }
            } else {
                BasicConfigurator basicConfigurator = new BasicConfigurator();
                basicConfigurator.setContext(loggerContext);
                basicConfigurator.configure(loggerContext);
            }
        }
    }

logback的默认配置,首先做了状态舰艇配置设置为默认的loggerContext上下文,看一下这里的设置,为何这么做
这个设置是在logback-core中操作的,
ch.qos.logback.core.util.StatusListenerConfigHelper

    public static void installIfAsked(Context context) {
        String slClass = OptionHelper.getSystemProperty(CoreConstants.STATUS_LISTENER_CLASS_KEY);
        if (!OptionHelper.isEmpty(slClass)) {
            addStatusListener(context, slClass);
        }
    }

这个代码中获取系统属性,有另一个常量,需要看一下具体是什么

java
final public static String STATUS_LISTENER_CLASS_KEY = "logback.statusListenerClass";

Ok ,知道变量内容,然后我们接着看,OptionHelper.getSystemProperty的方法
ch.qos.logback.core.OptionHelper

  public static String getSystemProperty(String key) {
        try {
            return System.getProperty(key);
        } catch (SecurityException e) {
            return null;
        }
    }

嗯知识获取监听类,如果有的话,把它加入状态监听,

    private static void addStatusListener(Context context, String listenerClassName) {
        StatusListener listener = null;
        if (CoreConstants.SYSOUT.equalsIgnoreCase(listenerClassName)) {
            listener = new OnConsoleStatusListener();
        } else {
            listener = createListenerPerClassName(context, listenerClassName);
        }
        initAndAddListener(context, listener);
    }

logback-core 中的 CoreConstants.SYSOUT常量

final public static String SYSOUT = "SYSOUT";

如果与监听类相同,那么新建控制台状态监听,否则createListenerPerClassName(context,listenerClassName)为指定的上下文,创建指定的监听类,咱们看一下是如何创建监听类的,方法如下
logback-core 中的 ch.qos.logback.core.util.StatusListenerConfigHelper

    private static StatusListener createListenerPerClassName(Context context, String listenerClass) {
        try {
            return (StatusListener) OptionHelper.instantiateByClassName(listenerClass, StatusListener.class, context);
        } catch (Exception e) {
            // printing on the console is the best we can do
            e.printStackTrace();
            return null;
        }
    }

根据类名创建监听类,估计是用了反射之类的技术,那么咱们就深入方法,一探究竟
logback-core 中的 ch.qos.logback.core.util.OptionHelper

    public static Object instantiateByClassName(String className, Class<?> superClass, Context context) throws IncompatibleClassException,
                    DynamicClassLoadingException {
        ClassLoader classLoader = Loader.getClassLoaderOfObject(context);
        return instantiateByClassName(className, superClass, classLoader);
    }

方法是很简单,通过方法名能看出是根据对象找到对应的类加载器,但是这块代码做了封装,咱们接着看Loader.getClassLoaderOfObject()方法,看他里面是如何实现的
logback-core中的ch.qos.logback.core.util.Loader

    public static ClassLoader getClassLoaderOfObject(Object o) {
        if (o == null) {
            throw new NullPointerException("Argument cannot be null");
        }
        return getClassLoaderOfClass(o.getClass());
    }

通过方法,可以看到里面又调用了,getClassLoaderOfClass(clazz)传递的参数是一个clazz,接着看

    public static ClassLoader getClassLoaderOfClass(final Class<?> clazz) {
        ClassLoader cl = clazz.getClassLoader();
        if (cl == null) {
            return ClassLoader.getSystemClassLoader();
        } else {
            return cl;
        }
    }

嗯,看到这里,依旧是,根据clazz获取对象的类加载器,如果没有的话,就用系统的类加载器,OK,得到类加载器之后,调用了instantiateByClassName(clazz,clazz,classLoader)的重载方法,看这个方法,里面是又如何处理的
logback-core 中的 ch.qos.logback.core.util.OptionHelper

    public static Object instantiateByClassName(String className, Class<?> superClass, ClassLoader classLoader) throws IncompatibleClassException,
                    DynamicClassLoadingException {
        return instantiateByClassNameAndParameter(className, superClass, classLoader, null, null);
    }

这里有调用了,通过类名和参数初始化类的方法instantiateByClassNameAndParameter()

    public static Object instantiateByClassNameAndParameter(String className, Class<?> superClass, ClassLoader classLoader, Class<?> type, Object parameter)
                    throws IncompatibleClassException, DynamicClassLoadingException {

        if (className == null) {
            throw new NullPointerException();
        }
        try {
            Class<?> classObj = null;
            classObj = classLoader.loadClass(className);
            if (!superClass.isAssignableFrom(classObj)) {
                throw new IncompatibleClassException(superClass, classObj);
            }
            if (type == null) {
                return classObj.newInstance();
            } else {
                Constructor<?> constructor = classObj.getConstructor(type);
                return constructor.newInstance(parameter);
            }
        } catch (IncompatibleClassException ice) {
            throw ice;
        } catch (Throwable t) {
            throw new DynamicClassLoadingException("Failed to instantiate type " + className, t);
        }
    }

方法,很简单,首先通过类加载器加载类,然后,判断加载的类与父类是否是继承关系,由于,类型为空那么到这里就是直接实例化了OK,到这里,上下文监听,
接下来该初始化和添加上下文的监听了,
logback-core中的 ch.qos.logback.core.util.StatusListenerConfigHelper

    private static void initAndAddListener(Context context, StatusListener listener) {
        if (listener != null) {
            if (listener instanceof ContextAware) // LOGBACK-767
                ((ContextAware) listener).setContext(context);

            boolean effectivelyAdded = context.getStatusManager().add(listener);
            if (effectivelyAdded && (listener instanceof LifeCycle)) {
                ((LifeCycle) listener).start(); // LOGBACK-767
            }
        }
    }

首先给监听设置上下文,然后,获取状态管理,并把监听添加进去,咱们先看一下获取状态监听的方法,由于getStatusManager是一个接口方法,我们在Context中看到,那么咱们看一下基础实现,然后在ContextBase实现类中找到如下的代码
logback-core中的ch.qos.logback.core.ContextBase

    public StatusManager getStatusManager() {
        return sm;
    }

直接返回了sm,那么sm是什么呢?通过查找定义,发现如下代码

    private StatusManager sm = new BasicStatusManager();

Ok,那么咱们就看一下基础状态管理是如何处理添加状态监听事件的找到如下方法
logback-core中的ch.qos.logback.core.BasicStatusManager

    public boolean add(StatusListener listener) {
        synchronized (statusListenerListLock) {
            if (listener instanceof OnConsoleStatusListener) {
                boolean alreadyPresent = checkForPresence(statusListenerList, listener.getClass());
                if (alreadyPresent)
                    return false;
            }
            statusListenerList.add(listener);
        }
        return true;
    }

代码中通过锁定状态监听集合对象 这个对象的作用是干什么呢,

final protected LogbackLock statusListenerListLock = new LogbackLock();

logbacklock 只是为了在分析线程时更容易识别的一个标志,本身无意义,但是能够让程序出问题是更容易分析

public class LogbackLock extends Object {

}

然后检查监听是否已经存在,如果存在,直接返回false,看一下如何检查是否存在的

    private boolean checkForPresence(List<StatusListener> statusListenerList, Class<?> aClass) {
        for (StatusListener e : statusListenerList) {
            if (e.getClass() == aClass)
                return true;
        }
        return false;
    }    
``
看完后发现是通过判断clazz,并没有利用list集合自带的方法来处理这个问题?这里需要考虑下为什么?不用集合自带的方法,是因为什么呢?
如果不存在的话,就直接通过集合的添加方法加进去了,嗯就是一个普通的集合,不过限制为只有子类才能访问,
```java
final protected List<StatusListener> statusListenerList = new ArrayList<StatusListener>();




<div class="se-preview-section-delimiter"></div>

接着看后面的方法,只有当添加成功,并且实现类LifeCycle的类会启动他,到这里,上下文监听,的内容已经彻底完结,通过start方法已经开始了运行,
看了多这么多的代码,我们接着回到我们autoConfig方法中,
第二行代码findURLOfDefaultConfigurationFile查找默认的配置文件
logback-classic中的ch.qos.logback.classic.util.ContextInitializer

    public URL findURLOfDefaultConfigurationFile(boolean updateStatus) {
        ClassLoader myClassLoader = Loader.getClassLoaderOfObject(this);
        URL url = findConfigFileURLFromSystemProperties(myClassLoader, updateStatus);
        if (url != null) {
            return url;
        }

        url = getResource(TEST_AUTOCONFIG_FILE, myClassLoader, updateStatus);
        if (url != null) {
            return url;
        }

        url = getResource(GROOVY_AUTOCONFIG_FILE, myClassLoader, updateStatus);
        if (url != null) {
            return url;
        }

        return getResource(AUTOCONFIG_FILE, myClassLoader, updateStatus);
    }





<div class="se-preview-section-delimiter"></div>

看看默认的配置文件是如何处理的,首先,第一行代码获取了家在当前类的类加载器,然后从系统属性中查找配置文件findConfigFileURLFromSystemProperties()
如何查找呢?
logback-classic中的ch.qos.logback.classic.util.ContextInitializer

    private URL findConfigFileURLFromSystemProperties(ClassLoader classLoader, boolean updateStatus) {
        String logbackConfigFile = OptionHelper.getSystemProperty(CONFIG_FILE_PROPERTY);
        if (logbackConfigFile != null) {
            URL result = null;
            try {
                result = new URL(logbackConfigFile);
                return result;
            } catch (MalformedURLException e) {
                // so, resource is not a URL:
                // attempt to get the resource from the class path
                result = Loader.getResource(logbackConfigFile, classLoader);
                if (result != null) {
                    return result;
                }
                File f = new File(logbackConfigFile);
                if (f.exists() && f.isFile()) {
                    try {
                        result = f.toURI().toURL();
                        return result;
                    } catch (MalformedURLException e1) {
                    }
                }
            } finally {
                if (updateStatus) {
                    statusOnResourceSearch(logbackConfigFile, classLoader, result);
                }
            }
        }
        return null;
    }




<div class="se-preview-section-delimiter"></div>

这里有一个CONFIG_FILE_PROPERTY属性,通过查找定义

    final public static String CONFIG_FILE_PROPERTY = "logback.configurationFile";




<div class="se-preview-section-delimiter"></div>

很简单,通过获取设置配置文件路径,然后判断设置的属性,如果位URL则直接实例化URL,并返回,如果不是,则查看是否是一个类资源配置文件,如果是直接返回对应的URL,如果不是,再查看是否是一个普通的文件路径,如果是则实例化文件对象,然后转换为URI,然后把URI转换为URL返回
由于,咱们没有配置这个参数,那么,直接往下面看代码 TEST_AUTOCONFIG_FILE ,看到这么个变量

final public static String TEST_AUTOCONFIG_FILE = "logback-test.xml";




<div class="se-preview-section-delimiter"></div>

如果有测试的配置文件,优先使用测试配置文件,如果有 GROOVY_AUTOCONFIG_FILE ,

    final public static String GROOVY_AUTOCONFIG_FILE = "logback.groovy";




<div class="se-preview-section-delimiter"></div>

如果以上都没有,那么最后的默认配置

 final public static String AUTOCONFIG_FILE = "logback.xml";




<div class="se-preview-section-delimiter"></div>

嗯,这里的等于说返回了配置文件所在的位置,如果有配置文件,
那么使用配置文件configureByResource()

    public void configureByResource(URL url) throws JoranException {
        if (url == null) {
            throw new IllegalArgumentException("URL argument cannot be null");
        }
        final String urlString = url.toString();
        if (urlString.endsWith("groovy")) {
            if (EnvUtil.isGroovyAvailable()) {
                // avoid directly referring to GafferConfigurator so as to avoid
                // loading groovy.lang.GroovyObject . See also http://jira.qos.ch/browse/LBCLASSIC-214
                GafferUtil.runGafferConfiguratorOn(loggerContext, this, url);
            } else {
                StatusManager sm = loggerContext.getStatusManager();
                sm.add(new ErrorStatus("Groovy classes are not available on the class path. ABORTING INITIALIZATION.", loggerContext));
            }
        } else if (urlString.endsWith("xml")) {
            JoranConfigurator configurator = new JoranConfigurator();
            configurator.setContext(loggerContext);
            configurator.doConfigure(url);
        } else {
            throw new LogbackException("Unexpected filename extension of file [" + url.toString() + "]. Should be either .groovy or .xml");
        }
    }




<div class="se-preview-section-delimiter"></div>

首先判断是groovy还是xml的,如果是groovy,那么先判断Groovy的环境是否可用,查看一下是如何判断的

    static public boolean isGroovyAvailable() {
        ClassLoader classLoader = Loader.getClassLoaderOfClass(EnvUtil.class);
        try {
            Class<?> bindingClass = classLoader.loadClass("groovy.lang.Binding");
            return (bindingClass != null);
        } catch (ClassNotFoundException e) {
            return false;
        }
    }




<div class="se-preview-section-delimiter"></div>

首先获取EnvUtil的类加载器,然后加载groovy.langBinding,如果不为空,则返回true,嗯,这里先不看groovy
先来查看xml的,首先初始化了JoranConfigurator,然后设置了,日志上下文,然后加载配置,咱们来看一下是如何加载配置,如何解析配置文件的
进入JoranConfigurator中并没有找到doConfigure,然后在他父类JoranConfiguratorBase的父类GenericConfigurator中找到了
logback-core 中的 ch.qos.logback.core.joran.GenericConfigurator

    public final void doConfigure(URL url) throws JoranException {
        InputStream in = null;
        try {
            informContextOfURLUsedForConfiguration(getContext(), url);
            URLConnection urlConnection = url.openConnection();
            // per http://jira.qos.ch/browse/LBCORE-105
            // per http://jira.qos.ch/browse/LBCORE-127
            urlConnection.setUseCaches(false);

            in = urlConnection.getInputStream();
            doConfigure(in, url.toExternalForm());
        } catch (IOException ioe) {
            String errMsg = "Could not open URL [" + url + "].";
            addError(errMsg, ioe);
            throw new JoranException(errMsg, ioe);
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException ioe) {
                    String errMsg = "Could not close input stream";
                    addError(errMsg, ioe);
                    throw new JoranException(errMsg, ioe);
                }
            }
        }
    }





<div class="se-preview-section-delimiter"></div>

先看第一行代码,通知用户上下文的配置
logback-core 中的 ch.qos.logback.core.joran.GenericConfigurator

  public static void informContextOfURLUsedForConfiguration(Context context, URL url) {
        ConfigurationWatchListUtil.setMainWatchURL(context, url);
    }




<div class="se-preview-section-delimiter"></div>

嗯,先不看通知的事,咱们先看一下,把配置文件解析为inputStrem和资源的外部来源后,要如何操作
logback-core 中的 ch.qos.logback.core.joran.GenericConfigurator

   public final void doConfigure(InputStream inputStream, String systemId) throws JoranException {
        InputSource inputSource = new InputSource(inputStream);
        inputSource.setSystemId(systemId);
        doConfigure(inputSource);
    }




<div class="se-preview-section-delimiter"></div>

然后根据inputstream创建了xml.sax解析的inputsource的对象,并把配置文件的外部来源设置为系统id,然后又调用了docConfigure方法
logback-core 中的 ch.qos.logback.core.joran.GenericConfigurator

 public final void doConfigure(final InputSource inputSource) throws JoranException {

        long threshold = System.currentTimeMillis();
        // if (!ConfigurationWatchListUtil.wasConfigurationWatchListReset(context)) {
        // informContextOfURLUsedForConfiguration(getContext(), null);
        // }
        SaxEventRecorder recorder = new SaxEventRecorder(context);
        recorder.recordEvents(inputSource);
        doConfigure(recorder.saxEventList);
        // no exceptions a this level
        StatusUtil statusUtil = new StatusUtil(context);
        if (statusUtil.noXMLParsingErrorsOccurred(threshold)) {
            addInfo("Registering current configuration as safe fallback point");
            registerSafeConfiguration(recorder.saxEventList);
        }
    }




<div class="se-preview-section-delimiter"></div>

首先获取当前时间的毫秒数,然后创建了Sax事件记录,然后吧配置文件的sax inputsource设置,解析配置文件集合
那么咱们先看,SaxEventRecorder中做了什么
logback-core 中的ch.qos.logback.core.joran.event.SaxEventRecorder

    public SaxEventRecorder(Context context) {
        cai = new ContextAwareImpl(context, this);
    }




<div class="se-preview-section-delimiter"></div>

嗯,其中创建了一个上下文感应实现,然后看一下recordEvents()中做了什么

    public List<SaxEvent> recordEvents(InputSource inputSource) throws JoranException {
        SAXParser saxParser = buildSaxParser();
        try {
            saxParser.parse(inputSource, this);
            return saxEventList;
        } catch (IOException ie) {
            handleError("I/O error occurred while parsing xml file", ie);
        } catch (SAXException se) {
            // Exception added into StatusManager via Sax error handling. No need to add it again
            throw new JoranException("Problem parsing XML document. See previously reported errors.", se);
        } catch (Exception ex) {
            handleError("Unexpected exception while parsing XML document.", ex);
        }
        throw new IllegalStateException("This point can never be reached");
    }




<div class="se-preview-section-delimiter"></div>

记录事件这个方法中做了什么呢,第一步先构建了SaxParser,

    private SAXParser buildSaxParser() throws JoranException {
        try {
            SAXParserFactory spf = SAXParserFactory.newInstance();
            spf.setValidating(false);
            spf.setNamespaceAware(true);
            return spf.newSAXParser();
        } catch (Exception pce) {
            String errMsg = "Parser configuration error occurred";
            addError(errMsg, pce);
            throw new JoranException(errMsg, pce);
        }
    }




<div class="se-preview-section-delimiter"></div>

嗯构建SaxParser,是通过SAXParserFactory工厂类实例的,,并且不设置验证,感知命名为空,然后通过工厂创建SaxParser,创建完SAXParser后就开始转换了

    public void parse(InputSource is, DefaultHandler dh)
        throws SAXException, IOException {
        if (is == null) {
            throw new IllegalArgumentException("InputSource cannot be null");
        }

        XMLReader reader = this.getXMLReader();
        if (dh != null) {
            reader.setContentHandler(dh);
            reader.setEntityResolver(dh);
            reader.setErrorHandler(dh);
            reader.setDTDHandler(dh);
        }
        reader.parse(is);
    }




<div class="se-preview-section-delimiter"></div>

解析xml需要一个输入源和默认的处理类,这里创建了一个XMLReader,然后reader.parse






<div class="se-preview-section-delimiter"></div>

嗯,上面利用SAX解析了xml后,把解析的内容都放到SAXEvent中,接着看doConfigure()

  public void doConfigure(final List<SaxEvent> eventList) throws JoranException {
        buildInterpreter();
        // disallow simultaneous configurations of the same context
        synchronized (context.getConfigurationLock()) {
            interpreter.getEventPlayer().play(eventList);
        }
    }




<div class="se-preview-section-delimiter"></div>

这里面第一个构建拦截器,然后为获取配置文件加锁,在拦截其中处理XML内容的具体解析,先来看一下buildInterpreter()方法中,做了什么,如何构建拦截器,这个拦截器的作用

    protected void buildInterpreter() {
        RuleStore rs = new SimpleRuleStore(context);
        addInstanceRules(rs);
        this.interpreter = new Interpreter(context, rs, initialElementPath());
        InterpretationContext interpretationContext = interpreter.getInterpretationContext();
        interpretationContext.setContext(context);
        addImplicitRules(interpreter);
        addDefaultNestedComponentRegistryRules(interpretationContext.getDefaultNestedComponentRegistry());
    }




<div class="se-preview-section-delimiter"></div>

首先构建了规则库,创建了简单的规则库,并传递了参数,然后增加拦截器规则,新建拦截器,获取拦截器上下文,添加
首先来看一下规则库,

  • 8
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值