Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
Copyright (c) 2004-2011 All rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 package org.slf4j;
 import java.util.List;
 import java.util.Set;
The LoggerFactory is a utility class producing Loggers for various logging APIs, most notably for log4j, logback and JDK 1.4 logging. Other implementations such as NOPLogger and SimpleLogger are also supported.

LoggerFactory is essentially a wrapper around an ILoggerFactory instance bound with LoggerFactory at compile time.

Please note that all methods in LoggerFactory are static.

Alexander Dorokhine
Robert Elliot
Ceki Gülcü
 public final class LoggerFactory {
     static final String CODES_PREFIX = "";
     static final String NO_STATICLOGGERBINDER_URL =  + "#StaticLoggerBinder";
     static final String MULTIPLE_BINDINGS_URL =  + "#multiple_bindings";
     static final String NULL_LF_URL =  + "#null_LF";
     static final String VERSION_MISMATCH =  + "#version_mismatch";
     static final String SUBSTITUTE_LOGGER_URL =  + "#substituteLogger";
     static final String LOGGER_NAME_MISMATCH_URL =  + "#loggerNameMismatch";
     static final String UNSUCCESSFUL_INIT_URL =  + "#unsuccessfulInit";
     static final String UNSUCCESSFUL_INIT_MSG = "org.slf4j.LoggerFactory could not be successfully initialized. See also " + ;
     static final int UNINITIALIZED = 0;
     static final int ONGOING_INITIALIZATION = 1;
     static final int FAILED_INITIALIZATION = 2;
     static final int SUCCESSFUL_INITIALIZATION = 3;
     static final int NOP_FALLBACK_INITIALIZATION = 4;
     static int INITIALIZATION_STATE = ;
     // Support for detecting mismatched logger names.
     static final String DETECT_LOGGER_NAME_MISMATCH_PROPERTY = "slf4j.detectLoggerNameMismatch";
     static boolean DETECT_LOGGER_NAME_MISMATCH = Boolean.getBoolean();

It is LoggerFactory's responsibility to track version changes and manage the compatibility list.

It is assumed that all versions in the 1.6 are mutually compatible.

     static private final String[] API_COMPATIBILITY_LIST = new String[] { "1.6""1.7" };
     // private constructor prevents instantiation
    private LoggerFactory() {

Force LoggerFactory to consider itself uninitialized.

This method is intended to be called by classes (in the same package) for testing purposes. This method is internal. It can be modified, renamed or removed at any time without notice.

You are strongly discouraged from calling this method in production code.

    static void reset() {
         = new SubstituteLoggerFactory();
    private final static void performInitialization() {
    private static boolean messageContainsOrgSlf4jImplStaticLoggerBinder(String msg) {
        if (msg == null)
            return false;
        if (msg.indexOf("org/slf4j/impl/StaticLoggerBinder") != -1)
            return true;
        if (msg.indexOf("org.slf4j.impl.StaticLoggerBinder") != -1)
            return true;
        return false;
    private final static void bind() {
        try {
            Set<URLstaticLoggerBinderPathSet = findPossibleStaticLoggerBinderPathSet();
            // the next line does the binding
        } catch (NoClassDefFoundError ncde) {
            String msg = ncde.getMessage();
            if (messageContainsOrgSlf4jImplStaticLoggerBinder(msg)) {
                 = ;
      "Failed to load class \"org.slf4j.impl.StaticLoggerBinder\".");
      "Defaulting to no-operation (NOP) logger implementation");
      "See " +  + " for further details.");
            } else {
                throw ncde;
        } catch (java.lang.NoSuchMethodError nsme) {
            String msg = nsme.getMessage();
            if (msg != null && msg.indexOf("org.slf4j.impl.StaticLoggerBinder.getSingleton()") != -1) {
                 = ;
      "slf4j-api 1.6.x (or later) is incompatible with this binding.");
      "Your binding is version 1.5.5 or earlier.");
      "Upgrade your binding to version 1.6.x.");
            throw nsme;
        } catch (Exception e) {
            throw new IllegalStateException("Unexpected initialization failure"e);
    static void failedBinding(Throwable t) {"Failed to instantiate SLF4J LoggerFactory"t);
    private final static void fixSubstitutedLoggers() {
        List<SubstituteLoggerloggers = .getLoggers();
        if (loggers.isEmpty()) {
        }"The following set of substitute loggers may have been accessed");"during the initialization phase. Logging calls during this");"phase were not honored. However, subsequent logging calls to these");"loggers will work as normally expected.");"See also " + );
        for (SubstituteLogger subLogger : loggers) {
    private final static void versionSanityCheck() {
        try {
            String requested = .;
            boolean match = false;
            for (int i = 0; i < .i++) {
                if (requested.startsWith([i])) {
                    match = true;
            if (!match) {
      "The requested version " + requested + " by your slf4j binding is not compatible with "
                                + Arrays.asList().toString());
      "See " +  + " for further details.");
        } catch (java.lang.NoSuchFieldError nsfe) {
            // given our large user base and SLF4J's commitment to backward
            // compatibility, we cannot cry here. Only for implementations
            // which willingly declare a REQUESTED_API_VERSION field do we
            // emit compatibility warnings.
        } catch (Throwable e) {
            // we should never reach here
  "Unexpected problem occured during version sanity check"e);
    // We need to use the name of the StaticLoggerBinder class, but we can't reference
    // the class itself.
    private static String STATIC_LOGGER_BINDER_PATH = "org/slf4j/impl/StaticLoggerBinder.class";
    private static Set<URLfindPossibleStaticLoggerBinderPathSet() {
        // use Set instead of list in order to deal with bug #138
        // LinkedHashSet appropriate here because it preserves insertion order during iteration
        Set<URLstaticLoggerBinderPathSet = new LinkedHashSet<URL>();
        try {
            ClassLoader loggerFactoryClassLoader = LoggerFactory.class.getClassLoader();
            if (loggerFactoryClassLoader == null) {
                paths = ClassLoader.getSystemResources();
            } else {
                paths = loggerFactoryClassLoader.getResources();
            while (paths.hasMoreElements()) {
                URL path = (URLpaths.nextElement();
        } catch (IOException ioe) {
  "Error getting resources from path"ioe);
        return staticLoggerBinderPathSet;
    private static boolean isAmbiguousStaticLoggerBinderPathSet(Set<URLstaticLoggerBinderPathSet) {
        return staticLoggerBinderPathSet.size() > 1;

Prints a warning message on the console if multiple bindings were found on the class path. No reporting is done otherwise.
    private static void reportMultipleBindingAmbiguity(Set<URLstaticLoggerBinderPathSet) {
        if (isAmbiguousStaticLoggerBinderPathSet(staticLoggerBinderPathSet)) {
  "Class path contains multiple SLF4J bindings.");
            Iterator<URLiterator = staticLoggerBinderPathSet.iterator();
            while (iterator.hasNext()) {
                URL path = (;
      "Found binding in [" + path + "]");
  "See " +  + " for an explanation.");
    private static void reportActualBinding(Set<URLstaticLoggerBinderPathSet) {
        if (isAmbiguousStaticLoggerBinderPathSet(staticLoggerBinderPathSet)) {
  "Actual binding is of type [" + StaticLoggerBinder.getSingleton().getLoggerFactoryClassStr() + "]");

Return a logger named according to the name parameter using the statically bound ILoggerFactory instance.

name The name of the logger.
    public static Logger getLogger(String name) {
        ILoggerFactory iLoggerFactory = getILoggerFactory();
        return iLoggerFactory.getLogger(name);

Return a logger named corresponding to the class passed as parameter, using the statically bound ILoggerFactory instance.

In case the the clazz parameter differs from the name of the caller as computed internally by SLF4J, a logger name mismatch warning will be printed but only if the slf4j.detectLoggerNameMismatch system property is set to true. By default, this property is not set and no warnings will be printed even in case of a logger name mismatch.

clazz the returned logger will be named after clazz
See also:
Detected logger name mismatch
    public static Logger getLogger(Class<?> clazz) {
        Logger logger = getLogger(clazz.getName());
        if () {
            Class<?> autoComputedCallingClass = Util.getCallingClass();
            if (nonMatchingClasses(clazzautoComputedCallingClass)) {
      "Detected logger name mismatch. Given name: \"%s\"; computed name: \"%s\"."logger.getName(),
      "See " +  + " for an explanation");
        return logger;
    private static boolean nonMatchingClasses(Class<?> clazzClass<?> autoComputedCallingClass) {
        return !autoComputedCallingClass.isAssignableFrom(clazz);

Return the ILoggerFactory instance in use.

ILoggerFactory instance is bound with this class at compile time.

the ILoggerFactory instance in use
    public static ILoggerFactory getILoggerFactory() {
        if ( == ) {
             = ;
        switch () {
        case :
            return StaticLoggerBinder.getSingleton().getLoggerFactory();
        case :
            return ;
        case :
            throw new IllegalStateException();
        case :
            // support re-entrant behavior.
            // See also
            return ;
        throw new IllegalStateException("Unreachable code");
New to GrepCode? Check out our FAQ X