001/*
002 * Logback: the reliable, generic, fast and flexible logging framework.
003 * Copyright (C) 1999-2026, QOS.ch. All rights reserved.
004 *
005 * This program and the accompanying materials are dual-licensed under
006 * either the terms of the Eclipse Public License v2.0 as published by
007 * the Eclipse Foundation
008 *
009 *   or (per the licensee's choosing)
010 *
011 * under the terms of the GNU Lesser General Public License version 2.1
012 * as published by the Free Software Foundation.
013 */
014package ch.qos.logback.classic.util;
015
016import ch.qos.logback.classic.ClassicConstants;
017import ch.qos.logback.classic.LoggerContext;
018import ch.qos.logback.classic.spi.Configurator;
019import ch.qos.logback.classic.spi.ConfiguratorRank;
020import ch.qos.logback.core.LogbackException;
021import ch.qos.logback.core.joran.spi.JoranException;
022import ch.qos.logback.core.spi.ContextAware;
023import ch.qos.logback.core.spi.ContextAwareImpl;
024import ch.qos.logback.core.util.CoreVersionUtil;
025import ch.qos.logback.core.util.Loader;
026import ch.qos.logback.core.util.StatusListenerConfigHelper;
027import ch.qos.logback.core.util.VersionUtil;
028
029import java.util.Comparator;
030import java.util.List;
031
032// contributors
033// Ted Graham, Matt Fowles, see also http://jira.qos.ch/browse/LBCORE-32
034
035/**
036 * This class contains logback's logic for automatic configuration
037 *
038 * @author Ceki Gulcu
039 */
040public class ContextInitializer {
041
042    /**
043     *  @deprecated Please use ClassicConstants.AUTOCONFIG_FILE instead
044     */
045    final public static String AUTOCONFIG_FILE = ClassicConstants.AUTOCONFIG_FILE;
046    /**
047     * @deprecated Please use ClassicConstants.TEST_AUTOCONFIG_FILE instead
048     */
049    final public static String TEST_AUTOCONFIG_FILE = ClassicConstants.TEST_AUTOCONFIG_FILE;
050    /**
051     * @deprecated Please use ClassicConstants.CONFIG_FILE_PROPERTY instead
052     */
053    final public static String CONFIG_FILE_PROPERTY = ClassicConstants.CONFIG_FILE_PROPERTY;
054
055    String[] INTERNAL_CONFIGURATOR_CLASSNAME_LIST = {"ch.qos.logback.classic.util.DefaultJoranConfigurator", "ch.qos.logback.classic.BasicConfigurator"};
056
057    final LoggerContext loggerContext;
058
059    final ContextAware contextAware;
060
061    public ContextInitializer(LoggerContext loggerContext) {
062        this.loggerContext = loggerContext;
063        this.contextAware = new ContextAwareImpl(loggerContext, this);
064    }
065
066    public void autoConfig() throws JoranException {
067        autoConfig(Configurator.class.getClassLoader());
068    }
069
070
071    public void autoConfig(ClassLoader classLoader) throws JoranException {
072
073        // see https://github.com/qos-ch/logback/issues/715
074        classLoader = Loader.systemClassloaderIfNull(classLoader);
075
076        checkVersions();
077
078        StatusListenerConfigHelper.installIfAsked(loggerContext);
079
080
081        // invoke custom configurators
082        List<Configurator> configuratorList = ClassicEnvUtil.loadFromServiceLoader(Configurator.class, classLoader);
083        configuratorList.sort(rankComparator);
084        if (configuratorList.isEmpty()) {
085            contextAware.addInfo("No custom configurators were discovered as a service.");
086        } else {
087            printConfiguratorOrder(configuratorList);
088        }
089
090        for (Configurator c : configuratorList) {
091            if (invokeConfigure(c) == Configurator.ExecutionStatus.DO_NOT_INVOKE_NEXT_IF_ANY)
092                return;
093        }
094
095        // invoke internal configurators
096        for (String configuratorClassName : INTERNAL_CONFIGURATOR_CLASSNAME_LIST) {
097            contextAware.addInfo("Trying to configure with "+configuratorClassName);
098            Configurator c = instantiateConfiguratorByClassName(configuratorClassName, classLoader);
099            if(c == null)
100                continue;
101            if (invokeConfigure(c) == Configurator.ExecutionStatus.DO_NOT_INVOKE_NEXT_IF_ANY)
102                return;
103        }
104    }
105
106    private void checkVersions() {
107        try {
108            String coreVersion = CoreVersionUtil.getCoreVersionBySelfDeclaredProperties();
109            String classicVersion = ClassicVersionUtil.getVersionBySelfDeclaredProperties();
110            VersionUtil.checkForVersionEquality(loggerContext, coreVersion, classicVersion, "logback-core", "logback-classic");
111        }  catch(NoClassDefFoundError e) {
112            contextAware.addWarn("Missing ch.logback.core.util.VersionUtil class on classpath. The version of logback-core is probably older than 1.5.26.");
113        } catch (NoSuchMethodError e) {
114            contextAware.addWarn(e.toString());
115            contextAware.addWarn("The version of logback-core is probably older than 1.5.26.");
116        }
117    }
118
119    private Configurator instantiateConfiguratorByClassName(String configuratorClassName, ClassLoader classLoader) {
120        try {
121            Class<?> classObj = classLoader.loadClass(configuratorClassName);
122            return (Configurator) classObj.getConstructor().newInstance();
123        } catch (ReflectiveOperationException  e) {
124            contextAware.addInfo("Instantiation failure: " + e.toString());
125            return null;
126        }
127    }
128
129    /**
130     *
131     * @param configurator
132     * @return ExecutionStatus
133     */
134    private Configurator.ExecutionStatus invokeConfigure(Configurator configurator) {
135        try {
136            long start = System.currentTimeMillis();
137            contextAware.addInfo("Constructed configurator of type " + configurator.getClass());
138            configurator.setContext(loggerContext);
139            Configurator.ExecutionStatus status = configurator.configure(loggerContext);
140            printDuration(start, configurator, status);
141            return status;
142
143        } catch (Exception e) {
144            throw new LogbackException(String.format("Failed to initialize or to run Configurator: %s",
145                    configurator != null ? configurator.getClass().getCanonicalName() : "null"), e);
146        }
147    }
148
149    private void printConfiguratorOrder(List<Configurator> configuratorList) {
150        contextAware.addInfo("Here is a list of configurators discovered as a service, by rank: ");
151        for(Configurator c: configuratorList) {
152            contextAware.addInfo("  "+c.getClass().getName());
153        }
154        contextAware.addInfo("They will be invoked in order until ExecutionStatus.DO_NOT_INVOKE_NEXT_IF_ANY is returned.");
155    }
156
157    private void printDuration(long start, Configurator configurator, Configurator.ExecutionStatus executionStatus) {
158        long end = System.currentTimeMillis();
159        long diff = end - start;
160        contextAware.addInfo( configurator.getClass().getName()+".configure() call lasted "+diff + " milliseconds. ExecutionStatus="+executionStatus);
161    }
162
163    private Configurator.ExecutionStatus attemptConfigurationUsingJoranUsingReflexion(ClassLoader classLoader) {
164
165        try {
166            Class<?> djcClass = classLoader.loadClass("ch.qos.logback.classic.util.DefaultJoranConfigurator");
167            Configurator c = (Configurator) djcClass.newInstance();
168            c.setContext(loggerContext);
169            return c.configure(loggerContext);
170        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
171            contextAware.addError("unexpected exception while instantiating DefaultJoranConfigurator", e);
172            return Configurator.ExecutionStatus.INVOKE_NEXT_IF_ANY;
173        }
174
175    }
176
177    Comparator<Configurator> rankComparator = new Comparator<Configurator>() {
178        @Override
179        public int compare(Configurator c1, Configurator c2) {
180
181            ConfiguratorRank r1 = c1.getClass().getAnnotation(ConfiguratorRank.class);
182            ConfiguratorRank r2 = c2.getClass().getAnnotation(ConfiguratorRank.class);
183
184            int value1 = r1 == null ? ConfiguratorRank.DEFAULT : r1.value();
185            int value2 = r2 == null ? ConfiguratorRank.DEFAULT : r2.value();
186
187            int result = compareRankValue(value1, value2);
188            // reverse the result for high to low sort
189            return (-result);
190        }
191    };
192
193    private int compareRankValue(int value1, int value2) {
194        if(value1 > value2)
195            return 1;
196        else if (value1 == value2)
197            return 0;
198        else return -1;
199
200    }
201}