001package ch.qos.logback.classic.spi; 002 003import org.slf4j.ILoggerFactory; 004import org.slf4j.IMarkerFactory; 005import org.slf4j.helpers.BasicMarkerFactory; 006import org.slf4j.helpers.Util; 007import org.slf4j.spi.MDCAdapter; 008import org.slf4j.spi.SLF4JServiceProvider; 009 010import ch.qos.logback.classic.LoggerContext; 011import ch.qos.logback.classic.util.ContextInitializer; 012import ch.qos.logback.classic.util.LogbackMDCAdapter; 013import ch.qos.logback.core.CoreConstants; 014import ch.qos.logback.core.joran.spi.JoranException; 015import ch.qos.logback.core.status.StatusUtil; 016import ch.qos.logback.core.util.StatusPrinter; 017 018public class LogbackServiceProvider implements SLF4JServiceProvider { 019 020 final static String NULL_CS_URL = CoreConstants.CODES_URL + "#null_CS"; 021 022 /** 023 * Declare the version of the SLF4J API this implementation is compiled against. 024 * The value of this field is modified with each major release. 025 */ 026 // to avoid constant folding by the compiler, this field must *not* be final 027 public static String REQUESTED_API_VERSION = "2.0.99"; // !final 028 029 private LoggerContext defaultLoggerContext = new LoggerContext(); 030 031 032 // org.slf4j.LoggerFactory expects providers to initialize markerFactory as early as possible. 033 private IMarkerFactory markerFactory = new BasicMarkerFactory(); 034 035 // org.slf4j.LoggerFactory expects providers to initialize their MDCAdapter field 036 // as early as possible, preferably at construction time. 037 private LogbackMDCAdapter mdcAdapter = new LogbackMDCAdapter(); 038 039 @Override 040 public void initialize() { 041 defaultLoggerContext.setName(CoreConstants.DEFAULT_CONTEXT_NAME); 042 // set the MDCAdapter for the defaultLoggerContext immediately 043 defaultLoggerContext.setMDCAdapter(mdcAdapter); 044 initializeLoggerContext(); 045 defaultLoggerContext.start(); 046 } 047 048 private void initializeLoggerContext() { 049 try { 050 try { 051 new ContextInitializer(defaultLoggerContext).autoConfig(); 052 } catch (JoranException je) { 053 Util.report("Failed to auto configure default logger context", je); 054 } 055 // LOGBACK-292 056 if (!StatusUtil.contextHasStatusListener(defaultLoggerContext)) { 057 StatusPrinter.printInCaseOfErrorsOrWarnings(defaultLoggerContext); 058 } 059 // contextSelectorBinder.init(defaultLoggerContext, KEY); 060 061 } catch (Exception t) { // see LOGBACK-1159 062 Util.report("Failed to instantiate [" + LoggerContext.class.getName() + "]", t); 063 } 064 } 065 066 @Override 067 068 public ILoggerFactory getLoggerFactory() { 069 return defaultLoggerContext; 070 } 071 072 @Override 073 public IMarkerFactory getMarkerFactory() { 074 return markerFactory; 075 } 076 077 @Override 078 public MDCAdapter getMDCAdapter() { 079 return mdcAdapter; 080 } 081 082 @Override 083 public String getRequestedApiVersion() { 084 return REQUESTED_API_VERSION; 085 } 086 087}