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