LogFactoryImpl.java

  1. /*
  2.  * Licensed to the Apache Software Foundation (ASF) under one or more
  3.  * contributor license agreements.  See the NOTICE file distributed with
  4.  * this work for additional information regarding copyright ownership.
  5.  * The ASF licenses this file to You under the Apache License, Version 2.0
  6.  * (the "License"); you may not use this file except in compliance with
  7.  * the License.  You may obtain a copy of the License at
  8.  *
  9.  *      http://www.apache.org/licenses/LICENSE-2.0
  10.  *
  11.  * Unless required by applicable law or agreed to in writing, software
  12.  * distributed under the License is distributed on an "AS IS" BASIS,
  13.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14.  * See the License for the specific language governing permissions and
  15.  * limitations under the License.
  16.  */

  17. package org.apache.commons.logging.impl;

  18. import java.io.PrintWriter;
  19. import java.io.StringWriter;
  20. import java.lang.reflect.Constructor;
  21. import java.lang.reflect.InvocationTargetException;
  22. import java.lang.reflect.Method;
  23. import java.net.URL;
  24. import java.security.AccessController;
  25. import java.security.PrivilegedAction;
  26. import java.util.Hashtable;

  27. import org.apache.commons.logging.Log;
  28. import org.apache.commons.logging.LogConfigurationException;
  29. import org.apache.commons.logging.LogFactory;

  30. /**
  31.  * Concrete subclass of {@link LogFactory} that implements the
  32.  * following algorithm to dynamically select a logging implementation
  33.  * class to instantiate a wrapper for:
  34.  * <ul>
  35.  * <li>Use a factory configuration attribute named
  36.  *     {@code org.apache.commons.logging.Log} to identify the
  37.  *     requested implementation class.</li>
  38.  * <li>Use the {@code org.apache.commons.logging.Log} system property
  39.  *     to identify the requested implementation class.</li>
  40.  * <li>If <em>Log4J</em> is available, return an instance of
  41.  *     {@code org.apache.commons.logging.impl.Log4JLogger}.</li>
  42.  * <li>If <em>JDK 1.4 or later</em> is available, return an instance of
  43.  *     {@code org.apache.commons.logging.impl.Jdk14Logger}.</li>
  44.  * <li>Otherwise, return an instance of
  45.  *     {@code org.apache.commons.logging.impl.SimpleLog}.</li>
  46.  * </ul>
  47.  * <p>
  48.  * If the selected {@link Log} implementation class has a
  49.  * {@code setLogFactory()} method that accepts a {@link LogFactory}
  50.  * parameter, this method will be called on each newly created instance
  51.  * to identify the associated factory.  This makes factory configuration
  52.  * attributes available to the Log instance, if it so desires.
  53.  * <p>
  54.  * This factory will remember previously created {@code Log} instances
  55.  * for the same name, and will return them on repeated requests to the
  56.  * {@code getInstance()} method.
  57.  */
  58. public class LogFactoryImpl extends LogFactory {

  59.     /** Log4JLogger class name */
  60.     private static final String LOGGING_IMPL_LOG4J_LOGGER = "org.apache.commons.logging.impl.Log4JLogger";
  61.     /** Jdk14Logger class name */
  62.     private static final String LOGGING_IMPL_JDK14_LOGGER = "org.apache.commons.logging.impl.Jdk14Logger";
  63.     /** Jdk13LumberjackLogger class name */
  64.     private static final String LOGGING_IMPL_LUMBERJACK_LOGGER =
  65.             "org.apache.commons.logging.impl.Jdk13LumberjackLogger";

  66.     /** SimpleLog class name */
  67.     private static final String LOGGING_IMPL_SIMPLE_LOGGER = "org.apache.commons.logging.impl.SimpleLog";

  68.     private static final String PKG_IMPL="org.apache.commons.logging.impl.";
  69.     private static final int PKG_LEN = PKG_IMPL.length();

  70.     /**
  71.      * An empty immutable {@code String} array.
  72.      */
  73.     private static final String[] EMPTY_STRING_ARRAY = {};

  74.     /**
  75.      * The name ({@code org.apache.commons.logging.Log}) of the system
  76.      * property identifying our {@link Log} implementation class.
  77.      */
  78.     public static final String LOG_PROPERTY = "org.apache.commons.logging.Log";

  79.     /**
  80.      * The deprecated system property used for backwards compatibility with
  81.      * old versions of JCL.
  82.      */
  83.     protected static final String LOG_PROPERTY_OLD = "org.apache.commons.logging.log";

  84.     /**
  85.      * The name ({@code org.apache.commons.logging.Log.allowFlawedContext})
  86.      * of the system property which can be set true/false to
  87.      * determine system behavior when a bad context class loader is encountered.
  88.      * When set to false, a LogConfigurationException is thrown if
  89.      * LogFactoryImpl is loaded via a child class loader of the TCCL (this
  90.      * should never happen in sane systems).
  91.      *
  92.      * Default behavior: true (tolerates bad context class loaders)
  93.      *
  94.      * See also method setAttribute.
  95.      */
  96.     public static final String ALLOW_FLAWED_CONTEXT_PROPERTY =
  97.         "org.apache.commons.logging.Log.allowFlawedContext";

  98.     /**
  99.      * The name ({@code org.apache.commons.logging.Log.allowFlawedDiscovery})
  100.      * of the system property which can be set true/false to
  101.      * determine system behavior when a bad logging adapter class is
  102.      * encountered during logging discovery. When set to false, an
  103.      * exception will be thrown and the app will fail to start. When set
  104.      * to true, discovery will continue (though the user might end up
  105.      * with a different logging implementation than they expected).
  106.      * <p>
  107.      * Default behavior: true (tolerates bad logging adapters)
  108.      *
  109.      * See also method setAttribute.
  110.      */
  111.     public static final String ALLOW_FLAWED_DISCOVERY_PROPERTY =
  112.         "org.apache.commons.logging.Log.allowFlawedDiscovery";

  113.     /**
  114.      * The name ({@code org.apache.commons.logging.Log.allowFlawedHierarchy})
  115.      * of the system property which can be set true/false to
  116.      * determine system behavior when a logging adapter class is
  117.      * encountered which has bound to the wrong Log class implementation.
  118.      * When set to false, an exception will be thrown and the app will fail
  119.      * to start. When set to true, discovery will continue (though the user
  120.      * might end up with a different logging implementation than they expected).
  121.      * <p>
  122.      * Default behavior: true (tolerates bad Log class hierarchy)
  123.      *
  124.      * See also method setAttribute.
  125.      */
  126.     public static final String ALLOW_FLAWED_HIERARCHY_PROPERTY =
  127.         "org.apache.commons.logging.Log.allowFlawedHierarchy";

  128.     /**
  129.      * The names of classes that will be tried (in order) as logging
  130.      * adapters. Each class is expected to implement the Log interface,
  131.      * and to throw NoClassDefFound or ExceptionInInitializerError when
  132.      * loaded if the underlying logging library is not available. Any
  133.      * other error indicates that the underlying logging library is available
  134.      * but broken/unusable for some reason.
  135.      */
  136.     private static final String[] classesToDiscover = {
  137.             LOGGING_IMPL_JDK14_LOGGER,
  138.             LOGGING_IMPL_SIMPLE_LOGGER
  139.     };

  140.     /**
  141.      * Workaround for bug in Java1.2; in theory this method is not needed. {@link LogFactory#getClassLoader(Class)}.
  142.      *
  143.      * @param clazz See {@link LogFactory#getClassLoader(Class)}.
  144.      * @return See {@link LogFactory#getClassLoader(Class)}.
  145.      * @since 1.1
  146.      */
  147.     protected static ClassLoader getClassLoader(final Class<?> clazz) {
  148.         return LogFactory.getClassLoader(clazz);
  149.     }

  150.     /**
  151.      * Gets the context ClassLoader.
  152.      * This method is a workaround for a Java 1.2 compiler bug.
  153.      *
  154.      * @return the context ClassLoader
  155.      * @since 1.1
  156.      */
  157.     protected static ClassLoader getContextClassLoader() throws LogConfigurationException {
  158.         return LogFactory.getContextClassLoader();
  159.     }

  160.     /**
  161.      * Calls LogFactory.directGetContextClassLoader under the control of an
  162.      * AccessController class. This means that Java code running under a
  163.      * security manager that forbids access to ClassLoaders will still work
  164.      * if this class is given appropriate privileges, even when the caller
  165.      * doesn't have such privileges. Without using an AccessController, the
  166.      * the entire call stack must have the privilege before the call is
  167.      * allowed.
  168.      *
  169.      * @return the context class loader associated with the current thread,
  170.      * or null if security doesn't allow it.
  171.      *
  172.      * @throws LogConfigurationException if there was some weird error while
  173.      * attempting to get the context class loader.
  174.      *
  175.      * @throws SecurityException if the current Java security policy doesn't
  176.      * allow this class to access the context class loader.
  177.      */
  178.     private static ClassLoader getContextClassLoaderInternal()
  179.             throws LogConfigurationException {
  180.         return AccessController.doPrivileged((PrivilegedAction<ClassLoader>) LogFactory::directGetContextClassLoader);
  181.     }

  182.     /**
  183.      * Read the specified system property, using an AccessController so that
  184.      * the property can be read if JCL has been granted the appropriate
  185.      * security rights even if the calling code has not.
  186.      * <p>
  187.      * Take care not to expose the value returned by this method to the
  188.      * calling application in any way; otherwise the calling app can use that
  189.      * info to access data that should not be available to it.
  190.      */
  191.     private static String getSystemProperty(final String key, final String def)
  192.             throws SecurityException {
  193.         return AccessController.doPrivileged((PrivilegedAction<String>) () -> System.getProperty(key, def));
  194.     }

  195.     /**
  196.      * Workaround for bug in Java1.2; in theory this method is not needed.
  197.      *
  198.      * @return Same as {@link LogFactory#isDiagnosticsEnabled()}.
  199.      * @see LogFactory#isDiagnosticsEnabled()
  200.      */
  201.     protected static boolean isDiagnosticsEnabled() {
  202.         return LogFactory.isDiagnosticsEnabled();
  203.     }

  204.     /** Utility method to safely trim a string. */
  205.     private static String trim(final String src) {
  206.         if (src == null) {
  207.             return null;
  208.         }
  209.         return src.trim();
  210.     }

  211.     /**
  212.      * Determines whether logging classes should be loaded using the thread-context
  213.      * class loader, or via the class loader that loaded this LogFactoryImpl class.
  214.      */
  215.     private boolean useTCCL = true;

  216.     /**
  217.      * The string prefixed to every message output by the logDiagnostic method.
  218.      */
  219.     private String diagnosticPrefix;

  220.     /**
  221.      * Configuration attributes.
  222.      */
  223.     protected Hashtable<String, Object> attributes = new Hashtable<>();

  224.     /**
  225.      * The {@link org.apache.commons.logging.Log} instances that have
  226.      * already been created, keyed by logger name.
  227.      */
  228.     protected Hashtable<String, Log> instances = new Hashtable<>();

  229.     /**
  230.      * Name of the class implementing the Log interface.
  231.      */
  232.     private String logClassName;

  233.     /**
  234.      * The one-argument constructor of the
  235.      * {@link org.apache.commons.logging.Log}
  236.      * implementation class that will be used to create new instances.
  237.      * This value is initialized by {@code getLogConstructor()},
  238.      * and then returned repeatedly.
  239.      */
  240.     protected Constructor<?> logConstructor;

  241.     /**
  242.      * The signature of the Constructor to be used.
  243.      */
  244.     protected Class<?>[] logConstructorSignature = { String.class };

  245.     /**
  246.      * The one-argument {@code setLogFactory} method of the selected
  247.      * {@link org.apache.commons.logging.Log} method, if it exists.
  248.      */
  249.     protected Method logMethod;

  250.     /**
  251.      * The signature of the {@code setLogFactory} method to be used.
  252.      */
  253.     protected Class<?>[] logMethodSignature = { LogFactory.class };

  254.     /**
  255.      * See getBaseClassLoader and initConfiguration.
  256.      */
  257.     private boolean allowFlawedContext;

  258.     /**
  259.      * See handleFlawedDiscovery and initConfiguration.
  260.      */
  261.     private boolean allowFlawedDiscovery;

  262.     /**
  263.      * See handleFlawedHierarchy and initConfiguration.
  264.      */
  265.     private boolean allowFlawedHierarchy;

  266.     /**
  267.      * Public no-arguments constructor required by the lookup mechanism.
  268.      */
  269.     public LogFactoryImpl() {
  270.         initDiagnostics();  // method on this object
  271.         if (isDiagnosticsEnabled()) {
  272.             logDiagnostic("Instance created.");
  273.         }
  274.     }

  275.     /**
  276.      * Attempts to load the given class, find a suitable constructor,
  277.      * and instantiate an instance of Log.
  278.      *
  279.      * @param logAdapterClassName class name of the Log implementation
  280.      * @param logCategory  argument to pass to the Log implementation's constructor
  281.      * @param affectState  {@code true} if this object's state should
  282.      *  be affected by this method call, {@code false} otherwise.
  283.      * @return  an instance of the given class, or null if the logging
  284.      *  library associated with the specified adapter is not available.
  285.      * @throws LogConfigurationException if there was a serious error with
  286.      *  configuration and the handleFlawedDiscovery method decided this
  287.      *  problem was fatal.
  288.      */
  289.     private Log createLogFromClass(final String logAdapterClassName,
  290.                                    final String logCategory,
  291.                                    final boolean affectState)
  292.         throws LogConfigurationException {

  293.         if (isDiagnosticsEnabled()) {
  294.             logDiagnostic("Attempting to instantiate '" + logAdapterClassName + "'");
  295.         }

  296.         final Object[] params = { logCategory };
  297.         Log logAdapter = null;
  298.         Constructor<?> constructor = null;

  299.         Class<?> logAdapterClass = null;
  300.         ClassLoader currentCL = getBaseClassLoader();

  301.         for(;;) {
  302.             // Loop through the class loader hierarchy trying to find
  303.             // a viable class loader.
  304.             logDiagnostic("Trying to load '" + logAdapterClassName + "' from class loader " + objectId(currentCL));
  305.             try {
  306.                 if (isDiagnosticsEnabled()) {
  307.                     // Show the location of the first occurrence of the .class file
  308.                     // in the classpath. This is the location that ClassLoader.loadClass
  309.                     // will load the class from -- unless the class loader is doing
  310.                     // something weird.
  311.                     URL url;
  312.                     final String resourceName = logAdapterClassName.replace('.', '/') + ".class";
  313.                     if (currentCL != null) {
  314.                         url = currentCL.getResource(resourceName );
  315.                     } else {
  316.                         url = ClassLoader.getSystemResource(resourceName + ".class");
  317.                     }

  318.                     if (url == null) {
  319.                         logDiagnostic("Class '" + logAdapterClassName + "' [" + resourceName + "] cannot be found.");
  320.                     } else {
  321.                         logDiagnostic("Class '" + logAdapterClassName + "' was found at '" + url + "'");
  322.                     }
  323.                 }

  324.                 Class<?> clazz;
  325.                 try {
  326.                     clazz = Class.forName(logAdapterClassName, true, currentCL);
  327.                 } catch (final ClassNotFoundException originalClassNotFoundException) {
  328.                     // The current class loader was unable to find the log adapter
  329.                     // in this or any ancestor class loader. There's no point in
  330.                     // trying higher up in the hierarchy in this case.
  331.                     String msg = originalClassNotFoundException.getMessage();
  332.                     logDiagnostic("The log adapter '" + logAdapterClassName + "' is not available via class loader " +
  333.                                   objectId(currentCL) + ": " + trim(msg));
  334.                     try {
  335.                         // Try the class class loader.
  336.                         // This may work in cases where the TCCL
  337.                         // does not contain the code executed or JCL.
  338.                         // This behavior indicates that the application
  339.                         // classloading strategy is not consistent with the
  340.                         // Java 1.2 classloading guidelines but JCL can
  341.                         // and so should handle this case.
  342.                         clazz = Class.forName(logAdapterClassName);
  343.                     } catch (final ClassNotFoundException secondaryClassNotFoundException) {
  344.                         // no point continuing: this adapter isn't available
  345.                         msg = secondaryClassNotFoundException.getMessage();
  346.                         logDiagnostic("The log adapter '" + logAdapterClassName +
  347.                                       "' is not available via the LogFactoryImpl class class loader: " + trim(msg));
  348.                         break;
  349.                     }
  350.                 }

  351.                 constructor = clazz.getConstructor(logConstructorSignature);
  352.                 final Object o = constructor.newInstance(params);

  353.                 // Note that we do this test after trying to create an instance
  354.                 // [rather than testing Log.class.isAssignableFrom(c)] so that
  355.                 // we don't complain about Log hierarchy problems when the
  356.                 // adapter couldn't be instantiated anyway.
  357.                 if (o instanceof Log) {
  358.                     logAdapterClass = clazz;
  359.                     logAdapter = (Log) o;
  360.                     break;
  361.                 }

  362.                 // Oops, we have a potential problem here. An adapter class
  363.                 // has been found and its underlying lib is present too, but
  364.                 // there are multiple Log interface classes available making it
  365.                 // impossible to cast to the type the caller wanted. We
  366.                 // certainly can't use this logger, but we need to know whether
  367.                 // to keep on discovering or terminate now.
  368.                 //
  369.                 // The handleFlawedHierarchy method will throw
  370.                 // LogConfigurationException if it regards this problem as
  371.                 // fatal, and just return if not.
  372.                 handleFlawedHierarchy(currentCL, clazz);
  373.             } catch (final NoClassDefFoundError e) {
  374.                 // We were able to load the adapter but it had references to
  375.                 // other classes that could not be found. This simply means that
  376.                 // the underlying logger library is not present in this or any
  377.                 // ancestor class loader. There's no point in trying higher up
  378.                 // in the hierarchy in this case.
  379.                 final String msg = e.getMessage();
  380.                 logDiagnostic("The log adapter '" + logAdapterClassName +
  381.                               "' is missing dependencies when loaded via class loader " + objectId(currentCL) +
  382.                               ": " + trim(msg));
  383.                 break;
  384.             } catch (final ExceptionInInitializerError e) {
  385.                 // A static initializer block or the initializer code associated
  386.                 // with a static variable on the log adapter class has thrown
  387.                 // an exception.
  388.                 //
  389.                 // We treat this as meaning the adapter's underlying logging
  390.                 // library could not be found.
  391.                 final String msg = e.getMessage();
  392.                 logDiagnostic("The log adapter '" + logAdapterClassName +
  393.                               "' is unable to initialize itself when loaded via class loader " + objectId(currentCL) +
  394.                               ": " + trim(msg));
  395.                 break;
  396.             } catch (final LogConfigurationException e) {
  397.                 // call to handleFlawedHierarchy above must have thrown
  398.                 // a LogConfigurationException, so just throw it on
  399.                 throw e;
  400.             } catch (final Throwable t) {
  401.                 handleThrowable(t); // may re-throw t
  402.                 // handleFlawedDiscovery will determine whether this is a fatal
  403.                 // problem or not. If it is fatal, then a LogConfigurationException
  404.                 // will be thrown.
  405.                 handleFlawedDiscovery(logAdapterClassName, t);
  406.             }

  407.             if (currentCL == null) {
  408.                 break;
  409.             }

  410.             // try the parent class loader
  411.             // currentCL = currentCL.getParent();
  412.             currentCL = getParentClassLoader(currentCL);
  413.         }

  414.         if (logAdapterClass != null && affectState) {
  415.             // We've succeeded, so set instance fields
  416.             this.logClassName   = logAdapterClassName;
  417.             this.logConstructor = constructor;

  418.             // Identify the {@code setLogFactory} method (if there is one)
  419.             try {
  420.                 this.logMethod = logAdapterClass.getMethod("setLogFactory", logMethodSignature);
  421.                 logDiagnostic("Found method setLogFactory(LogFactory) in '" + logAdapterClassName + "'");
  422.             } catch (final Throwable t) {
  423.                 handleThrowable(t); // may re-throw t
  424.                 this.logMethod = null;
  425.                 logDiagnostic("[INFO] '" + logAdapterClassName + "' from class loader " + objectId(currentCL) +
  426.                               " does not declare optional method " + "setLogFactory(LogFactory)");
  427.             }

  428.             logDiagnostic("Log adapter '" + logAdapterClassName + "' from class loader " +
  429.                           objectId(logAdapterClass.getClassLoader()) + " has been selected for use.");
  430.         }

  431.         return logAdapter;
  432.     }

  433.         // Static Methods
  434.     //
  435.     // These methods only defined as workarounds for a java 1.2 bug;
  436.     // theoretically none of these are needed.

  437.     /**
  438.      * Attempts to create a Log instance for the given category name.
  439.      * Follows the discovery process described in the class Javadoc.
  440.      *
  441.      * @param logCategory the name of the log category
  442.      * @throws LogConfigurationException if an error in discovery occurs,
  443.      * or if no adapter at all can be instantiated
  444.      */
  445.     private Log discoverLogImplementation(final String logCategory)
  446.         throws LogConfigurationException {
  447.         if (isDiagnosticsEnabled()) {
  448.             logDiagnostic("Discovering a Log implementation...");
  449.         }

  450.         initConfiguration();

  451.         Log result = null;

  452.         // See if the user specified the Log implementation to use
  453.         final String specifiedLogClassName = findUserSpecifiedLogClassName();

  454.         if (specifiedLogClassName != null) {
  455.             if (isDiagnosticsEnabled()) {
  456.                 logDiagnostic("Attempting to load user-specified log class '" +
  457.                     specifiedLogClassName + "'...");
  458.             }

  459.             result = createLogFromClass(specifiedLogClassName,
  460.                                         logCategory,
  461.                                         true);
  462.             if (result == null) {
  463.                 final StringBuilder messageBuffer =  new StringBuilder("User-specified log class '");
  464.                 messageBuffer.append(specifiedLogClassName);
  465.                 messageBuffer.append("' cannot be found or is not useable.");

  466.                 // Mistyping or misspelling names is a common fault.
  467.                 // Construct a good error message, if we can
  468.                 informUponSimilarName(messageBuffer, specifiedLogClassName, LOGGING_IMPL_LOG4J_LOGGER);
  469.                 informUponSimilarName(messageBuffer, specifiedLogClassName, LOGGING_IMPL_JDK14_LOGGER);
  470.                 informUponSimilarName(messageBuffer, specifiedLogClassName, LOGGING_IMPL_LUMBERJACK_LOGGER);
  471.                 informUponSimilarName(messageBuffer, specifiedLogClassName, LOGGING_IMPL_SIMPLE_LOGGER);
  472.                 throw new LogConfigurationException(messageBuffer.toString());
  473.             }

  474.             return result;
  475.         }

  476.         // No user specified log; try to discover what's on the classpath
  477.         //
  478.         // Note that we deliberately loop here over classesToDiscover and
  479.         // expect method createLogFromClass to loop over the possible source
  480.         // class loaders. The effect is:
  481.         //   for each discoverable log adapter
  482.         //      for each possible class loader
  483.         //          see if it works
  484.         //
  485.         // It appears reasonable at first glance to do the opposite:
  486.         //   for each possible class loader
  487.         //     for each discoverable log adapter
  488.         //        see if it works
  489.         //
  490.         // The latter certainly has advantages for user-installable logging
  491.         // libraries such as Log4j; in a webapp for example this code should
  492.         // first check whether the user has provided any of the possible
  493.         // logging libraries before looking in the parent class loader.
  494.         // Unfortunately, however, Jdk14Logger will always work in jvm>=1.4,
  495.         // and SimpleLog will always work in any JVM. So the loop would never
  496.         // ever look for logging libraries in the parent classpath. Yet many
  497.         // users would expect that putting Log4j there would cause it to be
  498.         // detected (and this is the historical JCL behavior). So we go with
  499.         // the first approach. A user that has bundled a specific logging lib
  500.         // in a webapp should use a commons-logging.properties file or a
  501.         // service file in META-INF to force use of that logging lib anyway,
  502.         // rather than relying on discovery.

  503.         if (isDiagnosticsEnabled()) {
  504.             logDiagnostic(
  505.                 "No user-specified Log implementation; performing discovery" +
  506.                 " using the standard supported logging implementations...");
  507.         }
  508.         for(int i=0; i<classesToDiscover.length && result == null; ++i) {
  509.             result = createLogFromClass(classesToDiscover[i], logCategory, true);
  510.         }

  511.         if (result == null) {
  512.             throw new LogConfigurationException
  513.                         ("No suitable Log implementation");
  514.         }

  515.         return result;
  516.     }

  517.     /**
  518.      * Checks system properties and the attribute map for
  519.      * a Log implementation specified by the user under the
  520.      * property names {@link #LOG_PROPERTY} or {@link #LOG_PROPERTY_OLD}.
  521.      *
  522.      * @return class name specified by the user, or {@code null}
  523.      */
  524.     private String findUserSpecifiedLogClassName() {
  525.         if (isDiagnosticsEnabled()) {
  526.             logDiagnostic("Trying to get log class from attribute '" + LOG_PROPERTY + "'");
  527.         }
  528.         String specifiedClass = (String) getAttribute(LOG_PROPERTY);

  529.         if (specifiedClass == null) { // @deprecated
  530.             if (isDiagnosticsEnabled()) {
  531.                 logDiagnostic("Trying to get log class from attribute '" +
  532.                               LOG_PROPERTY_OLD + "'");
  533.             }
  534.             specifiedClass = (String) getAttribute(LOG_PROPERTY_OLD);
  535.         }

  536.         if (specifiedClass == null) {
  537.             if (isDiagnosticsEnabled()) {
  538.                 logDiagnostic("Trying to get log class from system property '" +
  539.                           LOG_PROPERTY + "'");
  540.             }
  541.             try {
  542.                 specifiedClass = getSystemProperty(LOG_PROPERTY, null);
  543.             } catch (final SecurityException e) {
  544.                 if (isDiagnosticsEnabled()) {
  545.                     logDiagnostic("No access allowed to system property '" +
  546.                         LOG_PROPERTY + "' - " + e.getMessage());
  547.                 }
  548.             }
  549.         }

  550.         if (specifiedClass == null) { // @deprecated
  551.             if (isDiagnosticsEnabled()) {
  552.                 logDiagnostic("Trying to get log class from system property '" +
  553.                           LOG_PROPERTY_OLD + "'");
  554.             }
  555.             try {
  556.                 specifiedClass = getSystemProperty(LOG_PROPERTY_OLD, null);
  557.             } catch (final SecurityException e) {
  558.                 if (isDiagnosticsEnabled()) {
  559.                     logDiagnostic("No access allowed to system property '" +
  560.                         LOG_PROPERTY_OLD + "' - " + e.getMessage());
  561.                 }
  562.             }
  563.         }

  564.         // Remove any whitespace; it's never valid in a class name so its
  565.         // presence just means a user mistake. As we know what they meant,
  566.         // we may as well strip the spaces.
  567.         if (specifiedClass != null) {
  568.             specifiedClass = specifiedClass.trim();
  569.         }

  570.         return specifiedClass;
  571.     }

  572.     /**
  573.      * Gets the configuration attribute with the specified name (if any),
  574.      * or {@code null} if there is no such attribute.
  575.      *
  576.      * @param name Name of the attribute to return
  577.      */
  578.     @Override
  579.     public Object getAttribute(final String name) {
  580.         return attributes.get(name);
  581.     }

  582.     /**
  583.      * Gets an array containing the names of all currently defined
  584.      * configuration attributes.  If there are no such attributes, a zero
  585.      * length array is returned.
  586.      */
  587.     @Override
  588.     public String[] getAttributeNames() {
  589.         return attributes.keySet().toArray(EMPTY_STRING_ARRAY);
  590.     }

  591.     /**
  592.      * Gets the class loader from which we should try to load the logging
  593.      * adapter classes.
  594.      * <p>
  595.      * This method usually returns the context class loader. However if it
  596.      * is discovered that the class loader which loaded this class is a child
  597.      * of the context class loader <em>and</em> the allowFlawedContext option
  598.      * has been set then the class loader which loaded this class is returned
  599.      * instead.
  600.      * <p>
  601.      * The only time when the class loader which loaded this class is a
  602.      * descendant (rather than the same as or an ancestor of the context
  603.      * class loader) is when an app has created custom class loaders but
  604.      * failed to correctly set the context class loader. This is a bug in
  605.      * the calling application; however we provide the option for JCL to
  606.      * simply generate a warning rather than fail outright.
  607.      */
  608.     private ClassLoader getBaseClassLoader() throws LogConfigurationException {
  609.         final ClassLoader thisClassLoader = getClassLoader(LogFactoryImpl.class);

  610.         if (!useTCCL) {
  611.             return thisClassLoader;
  612.         }

  613.         final ClassLoader contextClassLoader = getContextClassLoaderInternal();

  614.         final ClassLoader baseClassLoader = getLowestClassLoader(
  615.                 contextClassLoader, thisClassLoader);

  616.         if (baseClassLoader == null) {
  617.            // The two class loaders are not part of a parent child relationship.
  618.            // In some classloading setups (e.g. JBoss with its
  619.            // UnifiedLoaderRepository) this can still work, so if user hasn't
  620.            // forbidden it, just return the contextClassLoader.
  621.            if (!allowFlawedContext) {
  622.             throw new LogConfigurationException("Bad class loader hierarchy; LogFactoryImpl was loaded via" +
  623.                                                 " a class loader that is not related to the current context" +
  624.                                                 " class loader.");
  625.            }
  626.         if (isDiagnosticsEnabled()) {
  627.                logDiagnostic("[WARNING] the context class loader is not part of a" +
  628.                              " parent-child relationship with the class loader that" +
  629.                              " loaded LogFactoryImpl.");
  630.           }
  631.           // If contextClassLoader were null, getLowestClassLoader() would
  632.           // have returned thisClassLoader.  The fact we are here means
  633.           // contextClassLoader is not null, so we can just return it.
  634.           return contextClassLoader;
  635.         }

  636.         if (baseClassLoader != contextClassLoader) {
  637.             // We really should just use the contextClassLoader as the starting
  638.             // point for scanning for log adapter classes. However it is expected
  639.             // that there are a number of broken systems out there which create
  640.             // custom class loaders but fail to set the context class loader so
  641.             // we handle those flawed systems anyway.
  642.             if (!allowFlawedContext) {
  643.                 throw new LogConfigurationException(
  644.                         "Bad class loader hierarchy; LogFactoryImpl was loaded via" +
  645.                         " a class loader that is not related to the current context" +
  646.                         " class loader.");
  647.             }
  648.             if (isDiagnosticsEnabled()) {
  649.                 logDiagnostic(
  650.                         "Warning: the context class loader is an ancestor of the" +
  651.                         " class loader that loaded LogFactoryImpl; it should be" +
  652.                         " the same or a descendant. The application using" +
  653.                         " commons-logging should ensure the context class loader" +
  654.                         " is used correctly.");
  655.             }
  656.         }

  657.         return baseClassLoader;
  658.     }

  659.     /**
  660.      * Gets the setting for the user-configurable behavior specified by key.
  661.      * If nothing has explicitly been set, then return dflt.
  662.      */
  663.     private boolean getBooleanConfiguration(final String key, final boolean dflt) {
  664.         final String val = getConfigurationValue(key);
  665.         if (val == null) {
  666.             return dflt;
  667.         }
  668.         return Boolean.parseBoolean(val);
  669.     }

  670.     /**
  671.      * Attempt to find an attribute (see method setAttribute) or a
  672.      * system property with the provided name and return its value.
  673.      * <p>
  674.      * The attributes associated with this object are checked before
  675.      * system properties in case someone has explicitly called setAttribute,
  676.      * or a configuration property has been set in a commons-logging.properties
  677.      * file.
  678.      *
  679.      * @return the value associated with the property, or null.
  680.      */
  681.     private String getConfigurationValue(final String property) {
  682.         if (isDiagnosticsEnabled()) {
  683.             logDiagnostic("[ENV] Trying to get configuration for item " + property);
  684.         }

  685.         final Object valueObj =  getAttribute(property);
  686.         if (valueObj != null) {
  687.             if (isDiagnosticsEnabled()) {
  688.                 logDiagnostic("[ENV] Found LogFactory attribute [" + valueObj + "] for " + property);
  689.             }
  690.             return valueObj.toString();
  691.         }

  692.         if (isDiagnosticsEnabled()) {
  693.             logDiagnostic("[ENV] No LogFactory attribute found for " + property);
  694.         }

  695.         try {
  696.             // warning: minor security hole here, in that we potentially read a system
  697.             // property that the caller cannot, then output it in readable form as a
  698.             // diagnostic message. However it's only ever JCL-specific properties
  699.             // involved here, so the harm is truly trivial.
  700.             final String value = getSystemProperty(property, null);
  701.             if (value != null) {
  702.                 if (isDiagnosticsEnabled()) {
  703.                     logDiagnostic("[ENV] Found system property [" + value + "] for " + property);
  704.                 }
  705.                 return value;
  706.             }

  707.             if (isDiagnosticsEnabled()) {
  708.                 logDiagnostic("[ENV] No system property found for property " + property);
  709.             }
  710.         } catch (final SecurityException e) {
  711.             if (isDiagnosticsEnabled()) {
  712.                 logDiagnostic("[ENV] Security prevented reading system property " + property);
  713.             }
  714.         }

  715.         if (isDiagnosticsEnabled()) {
  716.             logDiagnostic("[ENV] No configuration defined for item " + property);
  717.         }

  718.         return null;
  719.     }

  720.     /**
  721.      * Convenience method to derive a name from the specified class and
  722.      * call {@code getInstance(String)} with it.
  723.      *
  724.      * @param clazz Class for which a suitable Log name will be derived
  725.      * @throws LogConfigurationException if a suitable {@code Log}
  726.      *  instance cannot be returned
  727.      */
  728.     @Override
  729.     public Log getInstance(final Class<?> clazz) throws LogConfigurationException {
  730.         return getInstance(clazz.getName());
  731.     }

  732.     /**
  733.      * <p>Construct (if necessary) and return a {@code Log} instance,
  734.      * using the factory's current set of configuration attributes.</p>
  735.      *
  736.      * <p><strong>NOTE</strong> - Depending upon the implementation of
  737.      * the {@code LogFactory} you are using, the {@code Log}
  738.      * instance you are returned may or may not be local to the current
  739.      * application, and may or may not be returned again on a subsequent
  740.      * call with the same name argument.</p>
  741.      *
  742.      * @param name Logical name of the {@code Log} instance to be
  743.      *  returned (the meaning of this name is only known to the underlying
  744.      *  logging implementation that is being wrapped)
  745.      *
  746.      * @throws LogConfigurationException if a suitable {@code Log}
  747.      *  instance cannot be returned
  748.      */
  749.     @Override
  750.     public Log getInstance(final String name) throws LogConfigurationException {
  751.         return instances.computeIfAbsent(name, this::newInstance);
  752.     }

  753.     /**
  754.      * Gets the fully qualified Java class name of the {@link Log} implementation we will be using.
  755.      *
  756.      * @return the fully qualified Java class name of the {@link Log} implementation we will be using.
  757.      * @deprecated Never invoked by this class; subclasses should not assume it will be.
  758.      */
  759.     @Deprecated
  760.     protected String getLogClassName() {
  761.         if (logClassName == null) {
  762.             discoverLogImplementation(getClass().getName());
  763.         }

  764.         return logClassName;
  765.     }

  766.     /**
  767.      * <p>
  768.      * Gets the {@code Constructor} that can be called to instantiate new {@link org.apache.commons.logging.Log} instances.
  769.      * </p>
  770.      *
  771.      * <p>
  772.      * <strong>IMPLEMENTATION NOTE</strong> - Race conditions caused by calling this method from more than one thread are ignored, because the same
  773.      * {@code Constructor} instance will ultimately be derived in all circumstances.
  774.      * </p>
  775.      *
  776.      * @return the {@code Constructor} that can be called to instantiate new {@link org.apache.commons.logging.Log} instances.
  777.      * @throws LogConfigurationException if a suitable constructor cannot be returned
  778.      * @deprecated Never invoked by this class; subclasses should not assume it will be.
  779.      */
  780.     @Deprecated
  781.     protected Constructor<?> getLogConstructor()
  782.         throws LogConfigurationException {

  783.         // Return the previously identified Constructor (if any)
  784.         if (logConstructor == null) {
  785.             discoverLogImplementation(getClass().getName());
  786.         }

  787.         return logConstructor;
  788.     }

  789.     //  ------------------------------------------------------ Private Methods

  790.     /**
  791.      * Given two related class loaders, return the one which is a child of
  792.      * the other.
  793.      *
  794.      * @param c1 is a class loader (including the null class loader)
  795.      * @param c2 is a class loader (including the null class loader)
  796.      * @return c1 if it has c2 as an ancestor, c2 if it has c1 as an ancestor,
  797.      * and null if neither is an ancestor of the other.
  798.      */
  799.     private ClassLoader getLowestClassLoader(final ClassLoader c1, final ClassLoader c2) {
  800.         // TODO: use AccessController when dealing with class loaders here

  801.         if (c1 == null) {
  802.             return c2;
  803.         }

  804.         if (c2 == null) {
  805.             return c1;
  806.         }

  807.         ClassLoader current;

  808.         // scan c1's ancestors to find c2
  809.         current = c1;
  810.         while (current != null) {
  811.             if (current == c2) {
  812.                 return c1;
  813.             }
  814.             // current = current.getParent();
  815.             current = getParentClassLoader(current);
  816.         }

  817.         // scan c2's ancestors to find c1
  818.         current = c2;
  819.         while (current != null) {
  820.             if (current == c1) {
  821.                 return c2;
  822.             }
  823.             // current = current.getParent();
  824.             current = getParentClassLoader(current);
  825.         }

  826.         return null;
  827.     }

  828.     /**
  829.      * Fetch the parent class loader of a specified class loader.
  830.      * <p>
  831.      * If a SecurityException occurs, null is returned.
  832.      * <p>
  833.      * Note that this method is non-static merely so logDiagnostic is available.
  834.      */
  835.     private ClassLoader getParentClassLoader(final ClassLoader cl) {
  836.         try {
  837.             return AccessController.doPrivileged((PrivilegedAction<ClassLoader>) () -> cl.getParent());
  838.         } catch (final SecurityException ex) {
  839.             logDiagnostic("[SECURITY] Unable to obtain parent class loader");
  840.             return null;
  841.         }

  842.     }

  843.     /**
  844.      * Generates an internal diagnostic logging of the discovery failure and
  845.      * then throws a {@code LogConfigurationException} that wraps
  846.      * the passed {@code Throwable}.
  847.      *
  848.      * @param logAdapterClassName is the class name of the Log implementation
  849.      * that could not be instantiated. Cannot be {@code null}.
  850.      * @param discoveryFlaw is the Throwable created by the class loader
  851.      * @throws LogConfigurationException    ALWAYS
  852.      */
  853.     private void handleFlawedDiscovery(final String logAdapterClassName,
  854.                                        final Throwable discoveryFlaw) {

  855.         if (isDiagnosticsEnabled()) {
  856.             logDiagnostic("Could not instantiate Log '" +
  857.                       logAdapterClassName + "' -- " +
  858.                       discoveryFlaw.getClass().getName() + ": " +
  859.                       discoveryFlaw.getLocalizedMessage());

  860.             if (discoveryFlaw instanceof InvocationTargetException ) {
  861.                 // Ok, the lib is there but while trying to create a real underlying
  862.                 // logger something failed in the underlying lib; display info about
  863.                 // that if possible.
  864.                 final InvocationTargetException ite = (InvocationTargetException) discoveryFlaw;
  865.                 final Throwable cause = ite.getTargetException();
  866.                 if (cause != null) {
  867.                     logDiagnostic("... InvocationTargetException: " +
  868.                         cause.getClass().getName() + ": " +
  869.                         cause.getLocalizedMessage());

  870.                     if (cause instanceof ExceptionInInitializerError) {
  871.                         final ExceptionInInitializerError eiie = (ExceptionInInitializerError) cause;
  872.                         final Throwable cause2 = eiie.getCause();
  873.                         if (cause2 != null) {
  874.                             final StringWriter sw = new StringWriter();
  875.                             cause2.printStackTrace(new PrintWriter(sw, true));
  876.                             logDiagnostic("... ExceptionInInitializerError: " + sw.toString());
  877.                         }
  878.                     }
  879.                 }
  880.             }
  881.         }

  882.         if (!allowFlawedDiscovery) {
  883.             throw new LogConfigurationException(discoveryFlaw);
  884.         }
  885.     }

  886.     /**
  887.      * Report a problem loading the log adapter, then either return
  888.      * (if the situation is considered recoverable) or throw a
  889.      * LogConfigurationException.
  890.      * <p>
  891.      * There are two possible reasons why we successfully loaded the
  892.      * specified log adapter class then failed to cast it to a Log object:
  893.      * <ol>
  894.      * <li>the specific class just doesn't implement the Log interface
  895.      *     (user screwed up), or
  896.      * <li> the specified class has bound to a Log class loaded by some other
  897.      *      class loader; Log@ClassLoaderX cannot be cast to Log@ClassLoaderY.
  898.      * </ol>
  899.      * <p>
  900.      * Here we try to figure out which case has occurred so we can give the
  901.      * user some reasonable feedback.
  902.      *
  903.      * @param badClassLoader is the class loader we loaded the problem class from,
  904.      * ie it is equivalent to badClass.getClassLoader().
  905.      *
  906.      * @param badClass is a Class object with the desired name, but which
  907.      * does not implement Log correctly.
  908.      *
  909.      * @throws LogConfigurationException when the situation
  910.      * should not be recovered from.
  911.      */
  912.     private void handleFlawedHierarchy(final ClassLoader badClassLoader, final Class<?> badClass)
  913.         throws LogConfigurationException {

  914.         boolean implementsLog = false;
  915.         final String logInterfaceName = Log.class.getName();
  916.         final Class<?>[] interfaces = badClass.getInterfaces();
  917.         for (final Class<?> element : interfaces) {
  918.             if (logInterfaceName.equals(element.getName())) {
  919.                 implementsLog = true;
  920.                 break;
  921.             }
  922.         }

  923.         if (implementsLog) {
  924.             // the class does implement an interface called Log, but
  925.             // it is in the wrong class loader
  926.             if (isDiagnosticsEnabled()) {
  927.                 try {
  928.                     final ClassLoader logInterfaceClassLoader = getClassLoader(Log.class);
  929.                     logDiagnostic("Class '" + badClass.getName() + "' was found in class loader " +
  930.                                   objectId(badClassLoader) + ". It is bound to a Log interface which is not" +
  931.                                   " the one loaded from class loader " + objectId(logInterfaceClassLoader));
  932.                 } catch (final Throwable t) {
  933.                     handleThrowable(t); // may re-throw t
  934.                     logDiagnostic("Error while trying to output diagnostics about" + " bad class '" + badClass + "'");
  935.                 }
  936.             }

  937.             if (!allowFlawedHierarchy) {
  938.                 final StringBuilder msg = new StringBuilder();
  939.                 msg.append("Terminating logging for this context ");
  940.                 msg.append("due to bad log hierarchy. ");
  941.                 msg.append("You have more than one version of '");
  942.                 msg.append(Log.class.getName());
  943.                 msg.append("' visible.");
  944.                 if (isDiagnosticsEnabled()) {
  945.                     logDiagnostic(msg.toString());
  946.                 }
  947.                 throw new LogConfigurationException(msg.toString());
  948.             }

  949.             if (isDiagnosticsEnabled()) {
  950.                 final StringBuilder msg = new StringBuilder();
  951.                 msg.append("Warning: bad log hierarchy. ");
  952.                 msg.append("You have more than one version of '");
  953.                 msg.append(Log.class.getName());
  954.                 msg.append("' visible.");
  955.                 logDiagnostic(msg.toString());
  956.             }
  957.         } else {
  958.             // this is just a bad adapter class
  959.             if (!allowFlawedDiscovery) {
  960.                 final StringBuilder msg = new StringBuilder();
  961.                 msg.append("Terminating logging for this context. ");
  962.                 msg.append("Log class '");
  963.                 msg.append(badClass.getName());
  964.                 msg.append("' does not implement the Log interface.");
  965.                 if (isDiagnosticsEnabled()) {
  966.                     logDiagnostic(msg.toString());
  967.                 }

  968.                 throw new LogConfigurationException(msg.toString());
  969.             }

  970.             if (isDiagnosticsEnabled()) {
  971.                 final StringBuilder msg = new StringBuilder();
  972.                 msg.append("[WARNING] Log class '");
  973.                 msg.append(badClass.getName());
  974.                 msg.append("' does not implement the Log interface.");
  975.                 logDiagnostic(msg.toString());
  976.             }
  977.         }
  978.     }

  979.     /**
  980.      * Appends message if the given name is similar to the candidate.
  981.      * @param messageBuffer {@code StringBuffer} the message should be appended to,
  982.      * not null
  983.      * @param name the (trimmed) name to be test against the candidate, not null
  984.      * @param candidate the candidate name (not null)
  985.      */
  986.     private void informUponSimilarName(final StringBuilder messageBuffer, final String name,
  987.             final String candidate) {
  988.         if (name.equals(candidate)) {
  989.             // Don't suggest a name that is exactly the same as the one the
  990.             // user tried...
  991.             return;
  992.         }

  993.         // If the user provides a name that is in the right package, and gets
  994.         // the first 5 characters of the adapter class right (ignoring case),
  995.         // then suggest the candidate adapter class name.
  996.         if (name.regionMatches(true, 0, candidate, 0, PKG_LEN + 5)) {
  997.             messageBuffer.append(" Did you mean '");
  998.             messageBuffer.append(candidate);
  999.             messageBuffer.append("'?");
  1000.         }
  1001.     }

  1002.     /**
  1003.      * Initialize a number of variables that control the behavior of this
  1004.      * class and that can be tweaked by the user. This is done when the first
  1005.      * logger is created, not in the constructor of this class, because we
  1006.      * need to give the user a chance to call method setAttribute in order to
  1007.      * configure this object.
  1008.      */
  1009.     private void initConfiguration() {
  1010.         allowFlawedContext = getBooleanConfiguration(ALLOW_FLAWED_CONTEXT_PROPERTY, true);
  1011.         allowFlawedDiscovery = getBooleanConfiguration(ALLOW_FLAWED_DISCOVERY_PROPERTY, true);
  1012.         allowFlawedHierarchy = getBooleanConfiguration(ALLOW_FLAWED_HIERARCHY_PROPERTY, true);
  1013.     }

  1014.     /**
  1015.      * Calculate and cache a string that uniquely identifies this instance,
  1016.      * including which class loader the object was loaded from.
  1017.      * <p>
  1018.      * This string will later be prefixed to each "internal logging" message
  1019.      * emitted, so that users can clearly see any unexpected behavior.
  1020.      * <p>
  1021.      * Note that this method does not detect whether internal logging is
  1022.      * enabled or not, nor where to output stuff if it is; that is all
  1023.      * handled by the parent LogFactory class. This method just computes
  1024.      * its own unique prefix for log messages.
  1025.      */
  1026.     private void initDiagnostics() {
  1027.         // It would be nice to include an identifier of the context class loader
  1028.         // that this LogFactoryImpl object is responsible for. However that
  1029.         // isn't possible as that information isn't available. It is possible
  1030.         // to figure this out by looking at the logging from LogFactory to
  1031.         // see the context & impl ids from when this object was instantiated,
  1032.         // in order to link the impl id output as this object's prefix back to
  1033.         // the context it is intended to manage.
  1034.         // Note that this prefix should be kept consistent with that
  1035.         // in LogFactory.
  1036.         @SuppressWarnings("unchecked")
  1037.         final Class<LogFactoryImpl> clazz = (Class<LogFactoryImpl>) this.getClass();
  1038.         final ClassLoader classLoader = getClassLoader(clazz);
  1039.         String classLoaderName;
  1040.         try {
  1041.             if (classLoader == null) {
  1042.                 classLoaderName = "BOOTLOADER";
  1043.             } else {
  1044.                 classLoaderName = objectId(classLoader);
  1045.             }
  1046.         } catch (final SecurityException e) {
  1047.             classLoaderName = "UNKNOWN";
  1048.         }
  1049.         diagnosticPrefix = "[LogFactoryImpl@" + System.identityHashCode(this) + " from " + classLoaderName + "] ";
  1050.     }

  1051.     /**
  1052.      * Tests whether <em>JDK 1.3 with Lumberjack</em> logging available.
  1053.      *
  1054.      * @return whether <em>JDK 1.3 with Lumberjack</em> logging available.
  1055.      * @deprecated Never invoked by this class; subclasses should not assume it will be.
  1056.      */
  1057.     @Deprecated
  1058.     protected boolean isJdk13LumberjackAvailable() {
  1059.         return isLogLibraryAvailable(
  1060.                 "Jdk13Lumberjack",
  1061.                 "org.apache.commons.logging.impl.Jdk13LumberjackLogger");
  1062.     }

  1063.     /**
  1064.      * Tests {@code true} whether <em>JDK 1.4 or later</em> logging is available. Also checks that the {@code Throwable} class supports {@code getStackTrace()},
  1065.      * which is required by Jdk14Logger.
  1066.      *
  1067.      * @return Whether <em>JDK 1.4 or later</em> logging is available.
  1068.      * @deprecated Never invoked by this class; subclasses should not assume it will be.
  1069.      */
  1070.     @Deprecated
  1071.     protected boolean isJdk14Available() {
  1072.         return isLogLibraryAvailable("Jdk14", "org.apache.commons.logging.impl.Jdk14Logger");
  1073.     }

  1074.     /**
  1075.      * Tests whether a <em>Log4J</em> implementation available.
  1076.      *
  1077.      * @return whether a <em>Log4J</em> implementation available.
  1078.      * @deprecated Never invoked by this class; subclasses should not assume it will be.
  1079.      */
  1080.     @Deprecated
  1081.     protected boolean isLog4JAvailable() {
  1082.         return isLogLibraryAvailable("Log4J", LOGGING_IMPL_LOG4J_LOGGER);
  1083.     }

  1084.     /**
  1085.      * Utility method to check whether a particular logging library is
  1086.      * present and available for use. Note that this does <em>not</em>
  1087.      * affect the future behavior of this class.
  1088.      */
  1089.     private boolean isLogLibraryAvailable(final String name, final String className) {
  1090.         if (isDiagnosticsEnabled()) {
  1091.             logDiagnostic("Checking for '" + name + "'.");
  1092.         }
  1093.         try {
  1094.             final Log log = createLogFromClass(
  1095.                         className,
  1096.                         this.getClass().getName(), // dummy category
  1097.                         false);

  1098.             if (log == null) {
  1099.                 if (isDiagnosticsEnabled()) {
  1100.                     logDiagnostic("Did not find '" + name + "'.");
  1101.                 }
  1102.                 return false;
  1103.             }
  1104.             if (isDiagnosticsEnabled()) {
  1105.                 logDiagnostic("Found '" + name + "'.");
  1106.             }
  1107.             return true;
  1108.         } catch (final LogConfigurationException e) {
  1109.             if (isDiagnosticsEnabled()) {
  1110.                 logDiagnostic("Logging system '" + name + "' is available but not useable.");
  1111.             }
  1112.             return false;
  1113.         }
  1114.     }

  1115.     /**
  1116.      * Output a diagnostic message to a user-specified destination (if the
  1117.      * user has enabled diagnostic logging).
  1118.      *
  1119.      * @param msg diagnostic message
  1120.      * @since 1.1
  1121.      */
  1122.     protected void logDiagnostic(final String msg) {
  1123.         if (isDiagnosticsEnabled()) {
  1124.             logRawDiagnostic(diagnosticPrefix + msg);
  1125.         }
  1126.     }

  1127.     /**
  1128.      * Create and return a new {@link org.apache.commons.logging.Log} instance for the specified name.
  1129.      *
  1130.      * @param name Name of the new logger
  1131.      * @return a new {@link org.apache.commons.logging.Log}
  1132.      * @throws LogConfigurationException if a new instance cannot be created
  1133.      */
  1134.     protected Log newInstance(final String name) throws LogConfigurationException {
  1135.         Log instance;
  1136.         try {
  1137.             if (logConstructor == null) {
  1138.                 instance = discoverLogImplementation(name);
  1139.             }
  1140.             else {
  1141.                 final Object[] params = { name };
  1142.                 instance = (Log) logConstructor.newInstance(params);
  1143.             }

  1144.             if (logMethod != null) {
  1145.                 final Object[] params = { this };
  1146.                 logMethod.invoke(instance, params);
  1147.             }

  1148.             return instance;

  1149.         } catch (final LogConfigurationException lce) {

  1150.             // this type of exception means there was a problem in discovery
  1151.             // and we've already output diagnostics about the issue, etc.;
  1152.             // just pass it on
  1153.             throw lce;

  1154.         } catch (final InvocationTargetException e) {
  1155.             // A problem occurred invoking the Constructor or Method
  1156.             // previously discovered
  1157.             final Throwable c = e.getTargetException();
  1158.             throw new LogConfigurationException(c == null ? e : c);
  1159.         } catch (final Throwable t) {
  1160.             handleThrowable(t); // may re-throw t
  1161.             // A problem occurred invoking the Constructor or Method
  1162.             // previously discovered
  1163.             throw new LogConfigurationException(t);
  1164.         }
  1165.     }

  1166.     /**
  1167.      * Release any internal references to previously created
  1168.      * {@link org.apache.commons.logging.Log}
  1169.      * instances returned by this factory.  This is useful in environments
  1170.      * like servlet containers, which implement application reloading by
  1171.      * throwing away a ClassLoader.  Dangling references to objects in that
  1172.      * class loader would prevent garbage collection.
  1173.      */
  1174.     @Override
  1175.     public void release() {

  1176.         logDiagnostic("Releasing all known loggers");
  1177.         instances.clear();
  1178.     }

  1179.     /**
  1180.      * Remove any configuration attribute associated with the specified name.
  1181.      * If there is no such attribute, no action is taken.
  1182.      *
  1183.      * @param name Name of the attribute to remove
  1184.      */
  1185.     @Override
  1186.     public void removeAttribute(final String name) {
  1187.         attributes.remove(name);
  1188.     }

  1189.     /**
  1190.      * Sets the configuration attribute with the specified name.  Calling
  1191.      * this with a {@code null} value is equivalent to calling
  1192.      * {@code removeAttribute(name)}.
  1193.      * <p>
  1194.      * This method can be used to set logging configuration programmatically
  1195.      * rather than via system properties. It can also be used in code running
  1196.      * within a container (such as a webapp) to configure behavior on a
  1197.      * per-component level instead of globally as system properties would do.
  1198.      * To use this method instead of a system property, call
  1199.      * <pre>
  1200.      * LogFactory.getFactory().setAttribute(...)
  1201.      * </pre>
  1202.      * This must be done before the first Log object is created; configuration
  1203.      * changes after that point will be ignored.
  1204.      * <p>
  1205.      * This method is also called automatically if LogFactory detects a
  1206.      * commons-logging.properties file; every entry in that file is set
  1207.      * automatically as an attribute here.
  1208.      *
  1209.      * @param name Name of the attribute to set
  1210.      * @param value Value of the attribute to set, or {@code null}
  1211.      *  to remove any setting for this attribute
  1212.      */
  1213.     @Override
  1214.     public void setAttribute(final String name, final Object value) {
  1215.         if (logConstructor != null) {
  1216.             logDiagnostic("setAttribute: call too late; configuration already performed.");
  1217.         }

  1218.         if (value == null) {
  1219.             attributes.remove(name);
  1220.         } else {
  1221.             attributes.put(name, value);
  1222.         }

  1223.         if (name.equals(TCCL_KEY)) {
  1224.             useTCCL = value != null && Boolean.parseBoolean(value.toString());
  1225.         }
  1226.     }
  1227. }