logback源码解析之配置文件解析

logback源码解析之配置文件解析

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

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>

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






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

配置文件解析呢就是通过SAX解析的,那么咱们来看一下没有制定配置文件时,默认的配置是如何处理的
还是这个初始化类,ch.qos.logback.classic.util.ContextInitializer#autoConfig

    public void autoConfig() throws JoranException {
        StatusListenerConfigHelper.installIfAsked(loggerContext);
        URL url = findURLOfDefaultConfigurationFile(true);
        if (url != null) {
            configureByResource(url);
        } else {
            ///2222
            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);
            }
        }
    }




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

我们来看一下这个第二部分的内容,从ServiceLoader中加载配置文件,如果加载不到的话,就初始化一个基础的配置文件,咱们先来看一下,这个从服务加载器中加载配置
ch.qos.logback.classic.util.EnvUtil#loadFromServiceLoader

    public static <T> T loadFromServiceLoader(Class<T> c) {
        ServiceLoader<T> loader = ServiceLoader.load(c, getServiceLoaderClassLoader());
        Iterator<T> it = loader.iterator();
        if (it.hasNext())
            return it.next();
        return null;
    }




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

获取ServiceLoader的classLoader,搞明白这个serviceloader是什么类加载器?
ch.qos.logback.classic.util.EnvUtil#getServiceLoaderClassLoader

    private static ClassLoader getServiceLoaderClassLoader() {
        return testServiceLoaderClassLoader == null ? Loader.getClassLoaderOfClass(EnvUtil.class) : testServiceLoaderClassLoader;
    }




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

到这里就很明白了,如果是有测试服务类加载器就用测试的,如果没有的话, 就用EnvUtil的类加载器来加载配置文件,那么ServiceLoader的作用是什么呢?
SeriveLoader的作用是根据一个接口获取其所有子类实现,如果有的话取第一个实现,看一下基础的配置,都有什么

public class BasicConfigurator extends ContextAwareBase implements Configurator {

    public BasicConfigurator() {
    }

    public void configure(LoggerContext lc) {
        addInfo("Setting up default configuration.");

        ConsoleAppender<ILoggingEvent> ca = new ConsoleAppender<ILoggingEvent>();
        ca.setContext(lc);
        ca.setName("console");
        LayoutWrappingEncoder<ILoggingEvent> encoder = new LayoutWrappingEncoder<ILoggingEvent>();
        encoder.setContext(lc);


        // same as 
        // PatternLayout layout = new PatternLayout();
        // layout.setPattern("%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n");
        TTLLLayout layout = new TTLLLayout();

        layout.setContext(lc);
        layout.start();
        encoder.setLayout(layout);

        ca.setEncoder(encoder);
        ca.start();

        Logger rootLogger = lc.getLogger(Logger.ROOT_LOGGER_NAME);
        rootLogger.addAppender(ca);
    }
}

最简单的日至配置,有一个控制台日志打印, 至此所有的配置文件处理到此结束

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
集成logback.xml配置文件的步骤如下: 1. 首先,检查classpath下是否存在logback-test.xml文件。如果存在,则Logback将使用该文件作为配置文件。 2. 如果logback-test.xml文件不存在,则继续检查是否存在logback.xml文件。如果存在,则Logback将使用该文件作为配置文件。 3. 如果logback.xml文件也不存在,则Logback将默认使用BasicConfigurator进行自动配置。这将导致日志记录输出到控制台。 4. 在logback.xml配置文件中,可以定义日志的基本结构和各个元素的配置。一般而言,配置文件中会包含至少一个根logger元素,可以定义多个appender元素来指定日志输出的位置和方式,还可以定义多个logger元素来设置不同包或类的日志级别。 5. logback.xml文件中的配置可以使用PatternLayoutEncoder来指定日志输出的格式,可以使用level元素来设置日志级别。 总结起来,集成logback.xml配置文件的步骤包括检查存在的配置文件、定义日志结构和元素配置、指定日志输出位置和格式、设置日志级别等。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *3* [logback的使用详解和logback.xml配置文件](https://blog.csdn.net/yn_10073117/article/details/120362764)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] - *2* [SpringBoot集成slf4j日志和logback.xml配置详解](https://blog.csdn.net/qq_29864051/article/details/130881230)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值