001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017
018package org.apache.commons.logging;
019
020import java.io.FileOutputStream;
021import java.io.IOException;
022import java.io.InputStream;
023import java.io.PrintStream;
024import java.lang.ref.WeakReference;
025import java.net.URL;
026import java.net.URLConnection;
027import java.nio.charset.StandardCharsets;
028import java.security.AccessController;
029import java.security.PrivilegedAction;
030import java.util.Enumeration;
031import java.util.Hashtable;
032import java.util.Iterator;
033import java.util.Objects;
034import java.util.Properties;
035import java.util.ServiceConfigurationError;
036import java.util.ServiceLoader;
037import java.util.function.Supplier;
038
039/**
040 * Factory for creating {@link Log} instances, with discovery and
041 * configuration features similar to that employed by standard Java APIs
042 * such as JAXP.
043 * <p>
044 * <strong>IMPLEMENTATION NOTE</strong> - This implementation is heavily
045 * based on the SAXParserFactory and DocumentBuilderFactory implementations
046 * (corresponding to the JAXP pluggability APIs) found in Apache Xerces.
047 * </p>
048 */
049public abstract class LogFactory {
050    // Implementation note re AccessController usage
051    //
052    // It is important to keep code invoked via an AccessController to small
053    // auditable blocks. Such code must carefully evaluate all user input
054    // (parameters, system properties, configuration file contents, etc). As an
055    // example, a Log implementation should not write to its log file
056    // with an AccessController anywhere in the call stack, otherwise an
057    // insecure application could configure the log implementation to write
058    // to a protected file using the privileges granted to JCL rather than
059    // to the calling application.
060    //
061    // Under no circumstance should a non-private method return data that is
062    // retrieved via an AccessController. That would allow an insecure application
063    // to invoke that method and obtain data that it is not permitted to have.
064    //
065    // Invoking user-supplied code with an AccessController set is not a major
066    // issue (for example, invoking the constructor of the class specified by
067    // HASHTABLE_IMPLEMENTATION_PROPERTY). That class will be in a different
068    // trust domain, and therefore must have permissions to do whatever it
069    // is trying to do regardless of the permissions granted to JCL. There is
070    // a slight issue in that untrusted code may point that environment variable
071    // to another trusted library, in which case the code runs if both that
072    // library and JCL have the necessary permissions even when the untrusted
073    // caller does not. That's a pretty hard route to exploit though.
074
075    /**
076     * The name ({@code priority}) of the key in the configuration file used to
077     * specify the priority of that particular configuration file. The associated value
078     * is a floating-point number; higher values take priority over lower values.
079     */
080    public static final String PRIORITY_KEY = "priority";
081
082    /**
083     * The name ({@code use_tccl}) of the key in the configuration file used
084     * to specify whether logging classes should be loaded via the thread
085     * context class loader (TCCL), or not. By default, the TCCL is used.
086     */
087    public static final String TCCL_KEY = "use_tccl";
088
089    /**
090     * The name ({@code org.apache.commons.logging.LogFactory}) of the property
091     * used to identify the LogFactory implementation
092     * class name. This can be used as a system property, or as an entry in a
093     * configuration properties file.
094     */
095    public static final String FACTORY_PROPERTY = "org.apache.commons.logging.LogFactory";
096
097    private static final String FACTORY_LOG4J_API = "org.apache.commons.logging.impl.Log4jApiLogFactory";
098
099    private static final String LOG4J_TO_SLF4J_BRIDGE = "org.apache.logging.slf4j.SLF4JProvider";
100
101    private static final String FACTORY_SLF4J = "org.apache.commons.logging.impl.Slf4jLogFactory";
102
103    /**
104     * The fully qualified class name of the fallback {@code LogFactory}
105     * implementation class to use, if no other can be found.
106     */
107    public static final String FACTORY_DEFAULT = "org.apache.commons.logging.impl.LogFactoryImpl";
108
109    /**
110     * The name ({@code commons-logging.properties}) of the properties file to search for.
111     */
112    public static final String FACTORY_PROPERTIES = "commons-logging.properties";
113
114    /**
115     * JDK 1.3+ <a href="https://java.sun.com/j2se/1.3/docs/guide/jar/jar.html#Service%20Provider">
116     * 'Service Provider' specification</a>.
117     */
118    protected static final String SERVICE_ID = "META-INF/services/org.apache.commons.logging.LogFactory";
119
120    /**
121     * The name ({@code org.apache.commons.logging.diagnostics.dest})
122     * of the property used to enable internal commons-logging
123     * diagnostic output, in order to get information on what logging
124     * implementations are being discovered, what class loaders they
125     * are loaded through, etc.
126     * <p>
127     * If a system property of this name is set then the value is
128     * assumed to be the name of a file. The special strings
129     * STDOUT or STDERR (case-sensitive) indicate output to
130     * System.out and System.err respectively.
131     * <p>
132     * Diagnostic logging should be used only to debug problematic
133     * configurations and should not be set in normal production use.
134     */
135    public static final String DIAGNOSTICS_DEST_PROPERTY = "org.apache.commons.logging.diagnostics.dest";
136
137    /**
138     * When null (the usual case), no diagnostic output will be
139     * generated by LogFactory or LogFactoryImpl. When non-null,
140     * interesting events will be written to the specified object.
141     */
142    private static final PrintStream DIAGNOSTICS_STREAM;
143
144    /**
145     * A string that gets prefixed to every message output by the
146     * logDiagnostic method, so that users can clearly see which
147     * LogFactory class is generating the output.
148     */
149    private static final String DIAGNOSTICS_PREFIX;
150
151    /**
152     * Setting this system property
153     * ({@code org.apache.commons.logging.LogFactory.HashtableImpl})
154     * value allows the {@code Hashtable} used to store
155     * class loaders to be substituted by an alternative implementation.
156     * <p>
157     * <strong>Note:</strong> {@code LogFactory} will print:
158     * </p>
159     * <pre>
160     * [ERROR] LogFactory: Load of custom hash table failed
161     * </pre>
162     * <p>
163     * to system error and then continue using a standard Hashtable.
164     * </p>
165     * <p>
166     * <strong>Usage:</strong> Set this property when Java is invoked
167     * and {@code LogFactory} will attempt to load a new instance
168     * of the given implementation class.
169     * For example, running the following ant scriplet:
170     * </p>
171     * <pre>
172     *  &lt;java classname="${test.runner}" fork="yes" failonerror="${test.failonerror}"&gt;
173     *     ...
174     *     &lt;sysproperty
175     *        key="org.apache.commons.logging.LogFactory.HashtableImpl"
176     *        value="org.apache.commons.logging.AltHashtable"/&gt;
177     *  &lt;/java&gt;
178     * </pre>
179     * <p>
180     * will mean that {@code LogFactory} will load an instance of
181     * {@code org.apache.commons.logging.AltHashtable}.
182     * </p>
183     * <p>
184     * A typical use case is to allow a custom
185     * Hashtable implementation using weak references to be substituted.
186     * This will allow class loaders to be garbage collected without
187     * the need to release them (on 1.3+ JVMs only, of course ;).
188     * </p>
189     */
190    public static final String HASHTABLE_IMPLEMENTATION_PROPERTY = "org.apache.commons.logging.LogFactory.HashtableImpl";
191
192    /** Name used to load the weak hash table implementation by names. */
193    private static final String WEAK_HASHTABLE_CLASSNAME = "org.apache.commons.logging.impl.WeakHashtable";
194
195    /**
196     * A reference to the class loader that loaded this class. This is the
197     * same as LogFactory.class.getClassLoader(). However computing this
198     * value isn't quite as simple as that, as we potentially need to use
199     * AccessControllers etc. It's more efficient to compute it once and
200     * cache it here.
201     */
202    private static final WeakReference<ClassLoader> thisClassLoaderRef;
203
204    /**
205     * Maximum number of {@link ServiceLoader} errors to ignore, while
206     * looking for an implementation.
207     */
208    private static final int MAX_BROKEN_SERVICES = 3;
209
210    /**
211     * The previously constructed {@code LogFactory} instances, keyed by
212     * the {@code ClassLoader} with which it was created.
213     */
214    protected static Hashtable<ClassLoader, LogFactory> factories;
215
216    /**
217     * Previously constructed {@code LogFactory} instance as in the
218     * {@code factories} map, but for the case where
219     * {@code getClassLoader} returns {@code null}.
220     * This can happen when:
221     * <ul>
222     * <li>using JDK1.1 and the calling code is loaded via the system
223     *  class loader (very common)</li>
224     * <li>using JDK1.2+ and the calling code is loaded via the boot
225     *  class loader (only likely for embedded systems work).</li>
226     * </ul>
227     * Note that {@code factories} is a <em>Hashtable</em> (not a HashMap),
228     * and hash tables don't allow null as a key.
229     * @deprecated since 1.1.2
230     */
231    @Deprecated
232    protected static volatile LogFactory nullClassLoaderFactory;
233
234    static {
235        // note: it's safe to call methods before initDiagnostics (though
236        // diagnostic output gets discarded).
237        final ClassLoader thisClassLoader = getClassLoader(LogFactory.class);
238        thisClassLoaderRef = new WeakReference<>(thisClassLoader);
239        // In order to avoid confusion where multiple instances of JCL are
240        // being used via different class loaders within the same app, we
241        // ensure each logged message has a prefix of form
242        // [LogFactory from class loader OID]
243        //
244        // Note that this prefix should be kept consistent with that
245        // in LogFactoryImpl. However here we don't need to output info
246        // about the actual *instance* of LogFactory, as all methods that
247        // output diagnostics from this class are static.
248        String classLoaderName;
249        try {
250            classLoaderName = thisClassLoader != null ? objectId(thisClassLoader) : "BOOTLOADER";
251        } catch (final SecurityException e) {
252            classLoaderName = "UNKNOWN";
253        }
254        DIAGNOSTICS_PREFIX = "[LogFactory from " + classLoaderName + "] ";
255        DIAGNOSTICS_STREAM = initDiagnostics();
256        logClassLoaderEnvironment(LogFactory.class);
257        factories = createFactoryStore();
258        logDiagnostic("BOOTSTRAP COMPLETED");
259    }
260
261    /**
262     * Remember this factory, so later calls to LogFactory.getCachedFactory
263     * can return the previously created object (together with all its
264     * cached Log objects).
265     *
266     * @param classLoader should be the current context class loader. Note that
267     *  this can be null under some circumstances; this is ok.
268     * @param factory should be the factory to cache. This should never be null.
269     */
270    private static void cacheFactory(final ClassLoader classLoader, final LogFactory factory) {
271        // Ideally we would assert(factory != null) here. However reporting
272        // errors from within a logging implementation is a little tricky!
273        if (factory != null) {
274            if (classLoader == null) {
275                nullClassLoaderFactory = factory;
276            } else {
277                factories.put(classLoader, factory);
278            }
279        }
280    }
281
282    /**
283     * Creates a LogFactory object or a LogConfigurationException object.
284     *
285     * @param factoryClassName Factory class.
286     * @param classLoader      used to load the specified factory class. This is expected to be either the TCCL or the class loader which loaded this class.
287     *                         Note that the class loader which loaded this class might be "null" (for example, the boot loader) for embedded systems.
288     * @return either a LogFactory object or a LogConfigurationException object.
289     * @since 1.1
290     */
291    protected static Object createFactory(final String factoryClassName, final ClassLoader classLoader) {
292        // This will be used to diagnose bad configurations
293        // and allow a useful message to be sent to the user
294        Class<?> logFactoryClass = null;
295        try {
296            if (classLoader != null) {
297                try {
298                    // First the given class loader param (thread class loader)
299
300                    // Warning: must typecast here & allow exception
301                    // to be generated/caught & recast properly.
302                    logFactoryClass = classLoader.loadClass(factoryClassName);
303                    if (LogFactory.class.isAssignableFrom(logFactoryClass)) {
304                        if (isDiagnosticsEnabled()) {
305                            logDiagnostic("Loaded class " + logFactoryClass.getName() + " from class loader " + objectId(classLoader));
306                        }
307                    } else //
308                    // This indicates a problem with the ClassLoader tree.
309                    // An incompatible ClassLoader was used to load the
310                    // implementation.
311                    // As the same classes
312                    // must be available in multiple class loaders,
313                    // it is very likely that multiple JCL jars are present.
314                    // The most likely fix for this
315                    // problem is to remove the extra JCL jars from the
316                    // ClassLoader hierarchy.
317                    //
318                    if (isDiagnosticsEnabled()) {
319                        logDiagnostic("Factory class " + logFactoryClass.getName() + " loaded from class loader " + objectId(logFactoryClass.getClassLoader())
320                                + " does not extend '" + LogFactory.class.getName() + "' as loaded by this class loader.");
321                        logHierarchy("[BAD CL TREE] ", classLoader);
322                    }
323                    // Force a ClassCastException
324                    return LogFactory.class.cast(logFactoryClass.getConstructor().newInstance());
325
326                } catch (final ClassNotFoundException ex) {
327                    if (classLoader == thisClassLoaderRef.get()) {
328                        // Nothing more to try, onwards.
329                        if (isDiagnosticsEnabled()) {
330                            logDiagnostic("Unable to locate any class called '" + factoryClassName + "' via class loader " + objectId(classLoader));
331                        }
332                        throw ex;
333                    }
334                    // ignore exception, continue
335                } catch (final NoClassDefFoundError e) {
336                    if (classLoader == thisClassLoaderRef.get()) {
337                        // Nothing more to try, onwards.
338                        if (isDiagnosticsEnabled()) {
339                            logDiagnostic("Class '" + factoryClassName + "' cannot be loaded" + " via class loader " + objectId(classLoader)
340                                    + " - it depends on some other class that cannot be found.");
341                        }
342                        throw e;
343                    }
344                    // ignore exception, continue
345                } catch (final ClassCastException e) {
346                    if (classLoader == thisClassLoaderRef.get()) {
347                        // There's no point in falling through to the code below that
348                        // tries again with thisClassLoaderRef, because we've just tried
349                        // loading with that loader (not the TCCL). Just throw an
350                        // appropriate exception here.
351                        final boolean implementsLogFactory = implementsLogFactory(logFactoryClass);
352                        //
353                        // Construct a good message: users may not actual expect that a custom implementation
354                        // has been specified. Several well known containers use this mechanism to adapt JCL
355                        // to their native logging system.
356                        //
357                        final StringBuilder msg = new StringBuilder();
358                        msg.append("The application has specified that a custom LogFactory implementation should be used but Class '");
359                        msg.append(factoryClassName);
360                        msg.append("' cannot be converted to '");
361                        msg.append(LogFactory.class.getName());
362                        msg.append("'. ");
363                        if (implementsLogFactory) {
364                            msg.append("The conflict is caused by the presence of multiple LogFactory classes in incompatible class loaders. Background can");
365                            msg.append(" be found in https://commons.apache.org/logging/tech.html. If you have not explicitly specified a custom LogFactory");
366                            msg.append(" then it is likely that the container has set one without your knowledge. In this case, consider using the ");
367                            msg.append("commons-logging-adapters.jar file or specifying the standard LogFactory from the command line. ");
368                        } else {
369                            msg.append("Please check the custom implementation. ");
370                        }
371                        msg.append("Help can be found at https://commons.apache.org/logging/troubleshooting.html.");
372                        logDiagnostic(msg.toString());
373                        throw new ClassCastException(msg.toString());
374                    }
375                    // Ignore exception, continue. Presumably the class loader was the
376                    // TCCL; the code below will try to load the class via thisClassLoaderRef.
377                    // This will handle the case where the original calling class is in
378                    // a shared classpath but the TCCL has a copy of LogFactory and the
379                    // specified LogFactory implementation; we will fall back to using the
380                    // LogFactory implementation from the same class loader as this class.
381                    //
382                    // Issue: this doesn't handle the reverse case, where this LogFactory
383                    // is in the webapp, and the specified LogFactory implementation is
384                    // in a shared classpath. In that case:
385                    // (a) the class really does implement LogFactory (bad log msg above)
386                    // (b) the fallback code will result in exactly the same problem.
387                }
388            }
389
390            /*
391             * At this point, either classLoader == null, OR classLoader was unable to load factoryClass.
392             *
393             * In either case, we call Class.forName, which is equivalent to LogFactory.class.getClassLoader().load(name), that is, we ignore the class loader
394             * parameter the caller passed, and fall back to trying the class loader associated with this class. See the Javadoc for the newFactory method for
395             * more info on the consequences of this.
396             *
397             * Notes: * LogFactory.class.getClassLoader() may return 'null' if LogFactory is loaded by the bootstrap class loader.
398             */
399            // Warning: must typecast here & allow exception
400            // to be generated/caught & recast properly.
401            if (isDiagnosticsEnabled()) {
402                logDiagnostic(
403                        "Unable to load factory class via class loader " + objectId(classLoader) + " - trying the class loader associated with this LogFactory.");
404            }
405            logFactoryClass = Class.forName(factoryClassName);
406            // Force a ClassCastException
407            return LogFactory.class.cast(logFactoryClass.getConstructor().newInstance());
408        } catch (final Exception e) {
409            // Check to see if we've got a bad configuration
410            if (isDiagnosticsEnabled()) {
411                logDiagnostic("Unable to create LogFactory instance.");
412            }
413            if (logFactoryClass != null && !LogFactory.class.isAssignableFrom(logFactoryClass)) {
414                return new LogConfigurationException("The chosen LogFactory implementation does not extend LogFactory. Please check your configuration.", e);
415            }
416            return new LogConfigurationException(e);
417        }
418    }
419
420    /**
421     * Creates the hash table which will be used to store a map of
422     * (context class loader -> logfactory-object). Version 1.2+ of Java
423     * supports "weak references", allowing a custom Hashtable class
424     * to be used which uses only weak references to its keys. Using weak
425     * references can fix memory leaks on webapp unload in some cases (though
426     * not all). Version 1.1 of Java does not support weak references, so we
427     * must dynamically determine which we are using. And just for fun, this
428     * code also supports the ability for a system property to specify an
429     * arbitrary Hashtable implementation name.
430     * <p>
431     * Note that the correct way to ensure no memory leaks occur is to ensure
432     * that LogFactory.release(contextClassLoader) is called whenever a
433     * webapp is undeployed.
434     * </p>
435     */
436    private static Hashtable<ClassLoader, LogFactory> createFactoryStore() {
437        Hashtable<ClassLoader, LogFactory> result = null;
438        String storeImplementationClass;
439        try {
440            storeImplementationClass = getSystemProperty(HASHTABLE_IMPLEMENTATION_PROPERTY, null);
441        } catch (final SecurityException ex) {
442            // Permissions don't allow this to be accessed. Default to the "modern"
443            // weak hash table implementation if it is available.
444            storeImplementationClass = null;
445        }
446        if (storeImplementationClass == null) {
447            storeImplementationClass = WEAK_HASHTABLE_CLASSNAME;
448        }
449        try {
450            final Class<Hashtable<ClassLoader, LogFactory>> implementationClass = (Class<Hashtable<ClassLoader, LogFactory>>) Class
451                    .forName(storeImplementationClass);
452            result = implementationClass.getConstructor().newInstance();
453        } catch (final Throwable t) {
454            handleThrowable(t); // may re-throw t
455            // ignore
456            if (!WEAK_HASHTABLE_CLASSNAME.equals(storeImplementationClass)) {
457                // if the user's trying to set up a custom implementation, give a clue
458                if (isDiagnosticsEnabled()) {
459                    // use internal logging to issue the warning
460                    logDiagnostic("[ERROR] LogFactory: Load of custom Hashtable failed");
461                } else {
462                    // we *really* want this output, even if diagnostics weren't
463                    // explicitly enabled by the user.
464                    System.err.println("[ERROR] LogFactory: Load of custom Hashtable failed");
465                }
466            }
467        }
468        if (result == null) {
469            result = new Hashtable<>();
470        }
471        return result;
472    }
473
474    /**
475     * Gets the thread context class loader if available; otherwise return null.
476     * <p>
477     * Most/all code should call getContextClassLoaderInternal rather than
478     * calling this method directly.
479     * </p>
480     * <p>
481     * The thread context class loader is available for JDK 1.2
482     * or later, if certain security conditions are met.
483     * </p>
484     * <p>
485     * Note that no internal logging is done within this method because
486     * this method is called every time LogFactory.getLogger() is called,
487     * and we don't want too much output generated here.
488     * </p>
489     *
490     * @throws LogConfigurationException if a suitable class loader
491     *  cannot be identified.
492     * @return the thread's context class loader or {@code null} if the Java security
493     *  policy forbids access to the context class loader from one of the classes
494     *  in the current call stack.
495     * @since 1.1
496     */
497    protected static ClassLoader directGetContextClassLoader() throws LogConfigurationException {
498        ClassLoader classLoader = null;
499        try {
500            classLoader = Thread.currentThread().getContextClassLoader();
501        } catch (final SecurityException ignore) {
502            // getContextClassLoader() throws SecurityException when
503            // the context class loader isn't an ancestor of the
504            // calling class's class loader, or if security
505            // permissions are restricted.
506            //
507            // We ignore this exception to be consistent with the previous
508            // behavior (e.g. 1.1.3 and earlier).
509        }
510        // Return the selected class loader
511        return classLoader;
512    }
513
514    /**
515     * Gets a cached log factory (keyed by contextClassLoader)
516     *
517     * @param contextClassLoader is the context class loader associated
518     * with the current thread. This allows separate LogFactory objects
519     * per component within a container, provided each component has
520     * a distinct context class loader set. This parameter may be null
521     * in JDK1.1, and in embedded systems where jcl-using code is
522     * placed in the bootclasspath.
523     *
524     * @return the factory associated with the specified class loader if
525     *  one has previously been created, or null if this is the first time
526     *  we have seen this particular class loader.
527     */
528    private static LogFactory getCachedFactory(final ClassLoader contextClassLoader) {
529        if (contextClassLoader == null) {
530            // We have to handle this specially, as factories is a Hashtable
531            // and those don't accept null as a key value.
532            //
533            // nb: nullClassLoaderFactory might be null. That's ok.
534            return nullClassLoaderFactory;
535        }
536        return factories.get(contextClassLoader);
537    }
538
539    /**
540     * Safely get access to the class loader for the specified class.
541     * <p>
542     * Theoretically, calling getClassLoader can throw a security exception,
543     * and so should be done under an AccessController in order to provide
544     * maximum flexibility. However in practice people don't appear to use
545     * security policies that forbid getClassLoader calls. So for the moment
546     * all code is written to call this method rather than Class.getClassLoader,
547     * so that we could put AccessController stuff in this method without any
548     * disruption later if we need to.
549     * </p>
550     * <p>
551     * Even when using an AccessController, however, this method can still
552     * throw SecurityException. Commons Logging basically relies on the
553     * ability to access class loaders. A policy that forbids all
554     * class loader access will also prevent commons-logging from working:
555     * currently this method will throw an exception preventing the entire app
556     * from starting up. Maybe it would be good to detect this situation and
557     * just disable all commons-logging? Not high priority though - as stated
558     * above, security policies that prevent class loader access aren't common.
559     * </p>
560     * <p>
561     * Note that returning an object fetched via an AccessController would
562     * technically be a security flaw anyway; untrusted code that has access
563     * to a trusted JCL library could use it to fetch the class loader for
564     * a class even when forbidden to do so directly.
565     * </p>
566     *
567     * @param clazz Class.
568     * @return a ClassLoader.
569     * @since 1.1
570     */
571    protected static ClassLoader getClassLoader(final Class<?> clazz) {
572        try {
573            return clazz.getClassLoader();
574        } catch (final SecurityException ex) {
575            logDiagnostic(() -> "Unable to get class loader for class '" + clazz + "' due to security restrictions - " + ex.getMessage());
576            throw ex;
577        }
578    }
579
580    /**
581     * Gets a user-provided configuration file.
582     * <p>
583     * The classpath of the specified classLoader (usually the context class loader)
584     * is searched for properties files of the specified name. If none is found,
585     * null is returned. If more than one is found, then the file with the greatest
586     * value for its PRIORITY property is returned. If multiple files have the
587     * same PRIORITY value then the first in the classpath is returned.
588     * </p>
589     * <p>
590     * This differs from the 1.0.x releases; those always use the first one found.
591     * However as the priority is a new field, this change is backwards compatible.
592     * </p>
593     * <p>
594     * The purpose of the priority field is to allow a webserver administrator to
595     * override logging settings in all webapps by placing a commons-logging.properties
596     * file in a shared classpath location with a priority > 0; this overrides any
597     * commons-logging.properties files without priorities which are in the
598     * webapps. Webapps can also use explicit priorities to override a configuration
599     * file in the shared classpath if needed.
600     * </p>
601     */
602    private static Properties getConfigurationFile(final ClassLoader classLoader, final String fileName) {
603        Properties props = null;
604        double priority = 0.0;
605        URL propsUrl = null;
606        try {
607            final Enumeration<URL> urls = getResources(classLoader, fileName);
608            if (urls == null) {
609                return null;
610            }
611            while (urls.hasMoreElements()) {
612                final URL url = urls.nextElement();
613                final Properties newProps = getProperties(url);
614                if (newProps != null) {
615                    if (props == null) {
616                        propsUrl = url;
617                        props = newProps;
618                        final String priorityStr = props.getProperty(PRIORITY_KEY);
619                        priority = 0.0;
620                        if (priorityStr != null) {
621                            priority = Double.parseDouble(priorityStr);
622                        }
623                        if (isDiagnosticsEnabled()) {
624                            logDiagnostic("[LOOKUP] Properties file found at '" + url + "'" + " with priority " + priority);
625                        }
626                    } else {
627                        final String newPriorityStr = newProps.getProperty(PRIORITY_KEY);
628                        double newPriority = 0.0;
629                        if (newPriorityStr != null) {
630                            newPriority = Double.parseDouble(newPriorityStr);
631                        }
632                        if (newPriority > priority) {
633                            if (isDiagnosticsEnabled()) {
634                                logDiagnostic("[LOOKUP] Properties file at '" + url + "'" + " with priority " + newPriority + " overrides file at '" + propsUrl
635                                        + "'" + " with priority " + priority);
636                            }
637                            propsUrl = url;
638                            props = newProps;
639                            priority = newPriority;
640                        } else if (isDiagnosticsEnabled()) {
641                            logDiagnostic("[LOOKUP] Properties file at '" + url + "'" + " with priority " + newPriority + " does not override file at '"
642                                    + propsUrl + "'" + " with priority " + priority);
643                        }
644                    }
645
646                }
647            }
648        } catch (final SecurityException e) {
649            logDiagnostic("SecurityException thrown while trying to find/read config files.");
650        }
651        if (isDiagnosticsEnabled()) {
652            if (props == null) {
653                logDiagnostic("[LOOKUP] No properties file of name '" + fileName + "' found.");
654            } else {
655                logDiagnostic("[LOOKUP] Properties file of name '" + fileName + "' found at '" + propsUrl + '"');
656            }
657        }
658        return props;
659    }
660
661    /**
662     * Gets the current context class loader.
663     * <p>
664     * In versions prior to 1.1, this method did not use an AccessController.
665     * In version 1.1, an AccessController wrapper was incorrectly added to
666     * this method, causing a minor security flaw.
667     * </p>
668     * <p>
669     * In version 1.1.1 this change was reverted; this method no longer uses
670     * an AccessController. User code wishing to obtain the context class loader
671     * must invoke this method via AccessController.doPrivileged if it needs
672     * support for that.
673     * </p>
674     *
675     * @return the context class loader associated with the current thread,
676     *  or null if security doesn't allow it.
677     * @throws LogConfigurationException if there was some weird error while
678     *  attempting to get the context class loader.
679     */
680    protected static ClassLoader getContextClassLoader() throws LogConfigurationException {
681        return directGetContextClassLoader();
682    }
683
684    /**
685     * Calls {@link LogFactory#directGetContextClassLoader()} under the control of an
686     * AccessController class. This means that Java code running under a
687     * security manager that forbids access to ClassLoaders will still work
688     * if this class is given appropriate privileges, even when the caller
689     * doesn't have such privileges. Without using an AccessController, the
690     * the entire call stack must have the privilege before the call is
691     * allowed.
692     *
693     * @return the context class loader associated with the current thread,
694     *  or null if security doesn't allow it.
695     * @throws LogConfigurationException if there was some weird error while
696     *  attempting to get the context class loader.
697     */
698    private static ClassLoader getContextClassLoaderInternal() throws LogConfigurationException {
699        return AccessController.doPrivileged((PrivilegedAction<ClassLoader>) LogFactory::directGetContextClassLoader);
700    }
701
702    /**
703     * Constructs (if necessary) and return a {@code LogFactory} instance, using the following ordered lookup procedure to determine the name of the
704     * implementation class to be loaded.
705     * <ul>
706     * <li>The {@code org.apache.commons.logging.LogFactory} system property.</li>
707     * <li>The JDK 1.3 Service Discovery mechanism</li>
708     * <li>Use the properties file {@code commons-logging.properties} file, if found in the class path of this class. The configuration file is in standard
709     * {@link java.util.Properties} format and contains the fully qualified name of the implementation class with the key being the system property defined
710     * above.</li>
711     * <li>Fall back to a default implementation class ({@code org.apache.commons.logging.impl.LogFactoryImpl}).</li>
712     * </ul>
713     * <p>
714     * <em>NOTE</em> - If the properties file method of identifying the {@code LogFactory} implementation class is utilized, all of the properties defined in
715     * this file will be set as configuration attributes on the corresponding {@code LogFactory} instance.
716     * </p>
717     * <p>
718     * <em>NOTE</em> - In a multi-threaded environment it is possible that two different instances will be returned for the same class loader environment.
719     * </p>
720     *
721     * @return a {@code LogFactory}.
722     * @throws LogConfigurationException if the implementation class is not available or cannot be instantiated.
723     */
724    public static LogFactory getFactory() throws LogConfigurationException {
725        // Identify the class loader we will be using
726        final ClassLoader contextClassLoader = getContextClassLoaderInternal();
727
728        // This is an odd enough situation to report about. This
729        // output will be a nuisance on JDK1.1, as the system
730        // class loader is null in that environment.
731        if (contextClassLoader == null) {
732            logDiagnostic("Context class loader is null.");
733        }
734
735        // Return any previously registered factory for this class loader
736        LogFactory factory = getCachedFactory(contextClassLoader);
737        if (factory != null) {
738            return factory;
739        }
740
741        if (isDiagnosticsEnabled()) {
742            logDiagnostic(
743                    "[LOOKUP] LogFactory implementation requested for the first time for context class loader " +
744                    objectId(contextClassLoader));
745            logHierarchy("[LOOKUP] ", contextClassLoader);
746        }
747
748        // Load properties file.
749        //
750        // If the properties file exists, then its contents are used as
751        // "attributes" on the LogFactory implementation class. One particular
752        // property may also control which LogFactory concrete subclass is
753        // used, but only if other discovery mechanisms fail.
754        //
755        // As the properties file (if it exists) will be used one way or
756        // another in the end we may as well look for it first.
757
758        final Properties props = getConfigurationFile(contextClassLoader, FACTORY_PROPERTIES);
759
760        // Determine whether we will be using the thread context class loader to
761        // load logging classes or not by checking the loaded properties file (if any).
762        boolean useTccl = contextClassLoader != null;
763        if (props != null) {
764            final String useTCCLStr = props.getProperty(TCCL_KEY);
765            useTccl &= useTCCLStr == null || Boolean.parseBoolean(useTCCLStr);
766        }
767        // If TCCL is still enabled at this point, we check if it resolves this class
768        if (useTccl) {
769            try {
770                if (!LogFactory.class.equals(Class.forName(LogFactory.class.getName(), false, contextClassLoader))) {
771                    logDiagnostic(() -> "The class " + LogFactory.class.getName() + " loaded by the context class loader " + objectId(contextClassLoader)
772                            + " and this class differ. Disabling the usage of the context class loader."
773                            + "Background can be found in https://commons.apache.org/logging/tech.html. ");
774                    logHierarchy("[BAD CL TREE] ", contextClassLoader);
775                    useTccl = false;
776                }
777            } catch (final ClassNotFoundException ignored) {
778                logDiagnostic(() -> "The class " + LogFactory.class.getName() + " is not present in the the context class loader "
779                        + objectId(contextClassLoader) + ". Disabling the usage of the context class loader."
780                        + "Background can be found in https://commons.apache.org/logging/tech.html. ");
781                logHierarchy("[BAD CL TREE] ", contextClassLoader);
782                useTccl = false;
783            }
784        }
785        final ClassLoader baseClassLoader = useTccl ? contextClassLoader : thisClassLoaderRef.get();
786
787        // Determine which concrete LogFactory subclass to use.
788        // First, try a global system property
789        logDiagnostic(() -> "[LOOKUP] Looking for system property [" + FACTORY_PROPERTY +
790                      "] to define the LogFactory subclass to use...");
791
792        try {
793            final String factoryClass = getSystemProperty(FACTORY_PROPERTY, null);
794            if (factoryClass != null) {
795                logDiagnostic(() -> "[LOOKUP] Creating an instance of LogFactory class '" + factoryClass +
796                              "' as specified by system property " + FACTORY_PROPERTY);
797                factory = newFactory(factoryClass, baseClassLoader, contextClassLoader);
798            } else {
799                logDiagnostic(() -> "[LOOKUP] No system property [" + FACTORY_PROPERTY + "] defined.");
800            }
801        } catch (final SecurityException e) {
802            logDiagnostic(() -> "[LOOKUP] A security exception occurred while trying to create an instance of the custom factory class" + ": ["
803                    + trim(e.getMessage()) + "]. Trying alternative implementations...");
804            // ignore
805        } catch (final RuntimeException e) {
806            // This is not consistent with the behavior when a bad LogFactory class is
807            // specified in a services file.
808            //
809            // One possible exception that can occur here is a ClassCastException when
810            // the specified class wasn't castable to this LogFactory type.
811            logDiagnostic(() -> "[LOOKUP] An exception occurred while trying to create an instance of the custom factory class: [" + trim(e.getMessage())
812                    + "] as specified by a system property.");
813            throw e;
814        }
815        //
816        // Second, try to find a service by using the JDK 1.3 class
817        // discovery mechanism, which involves putting a file with the name
818        // of an interface class in the META-INF/services directory, where the
819        // contents of the file is a single line specifying a concrete class
820        // that implements the desired interface.
821        if (factory == null) {
822            logDiagnostic("[LOOKUP] Using ServiceLoader  to define the LogFactory subclass to use...");
823            try {
824                final ServiceLoader<LogFactory> serviceLoader = ServiceLoader.load(LogFactory.class, baseClassLoader);
825                final Iterator<LogFactory> iterator = serviceLoader.iterator();
826
827                int i = MAX_BROKEN_SERVICES;
828                while (factory == null && i-- > 0) {
829                    try {
830                        if (iterator.hasNext()) {
831                            factory = iterator.next();
832                        }
833                    } catch (final ServiceConfigurationError | LinkageError ex) {
834                        logDiagnostic(() -> "[LOOKUP] An exception occurred while trying to find an instance of LogFactory: [" + trim(ex.getMessage())
835                                + "]. Trying alternative implementations...");
836                    }
837                }
838            } catch (final Exception ex) {
839                // note: if the specified LogFactory class wasn't compatible with LogFactory
840                // for some reason, a ClassCastException will be caught here, and attempts will
841                // continue to find a compatible class.
842                logDiagnostic(() -> "[LOOKUP] A security exception occurred while trying to create an instance of the custom factory class: ["
843                        + trim(ex.getMessage()) + "]. Trying alternative implementations...");
844                // ignore
845            }
846        }
847        //
848        // Third try looking into the properties file read earlier (if found)
849        if (factory == null) {
850            if (props != null) {
851                logDiagnostic(() ->
852                    "[LOOKUP] Looking in properties file for entry with key '" + FACTORY_PROPERTY +
853                    "' to define the LogFactory subclass to use...");
854                final String factoryClass = props.getProperty(FACTORY_PROPERTY);
855                if (factoryClass != null) {
856                    logDiagnostic(() ->
857                        "[LOOKUP] Properties file specifies LogFactory subclass '" + factoryClass + "'");
858                    factory = newFactory(factoryClass, baseClassLoader, contextClassLoader);
859                    // TODO: think about whether we need to handle exceptions from newFactory
860                } else {
861                    logDiagnostic("[LOOKUP] Properties file has no entry specifying LogFactory subclass.");
862                }
863            } else {
864                logDiagnostic("[LOOKUP] No properties file available to determine LogFactory subclass from..");
865            }
866        }
867        //
868        // Fourth, try one of the three provided factories first from the specified classloader
869        // and then from the current one.
870        if (factory == null) {
871            factory = newStandardFactory(baseClassLoader);
872        }
873        if (factory == null && baseClassLoader != thisClassLoaderRef.get()) {
874            factory = newStandardFactory(thisClassLoaderRef.get());
875        }
876        if (factory != null) {
877            if (isDiagnosticsEnabled()) {
878                logDiagnostic("Created object " + objectId(factory) + " to manage class loader " + objectId(contextClassLoader));
879            }
880        } else {
881            logDiagnostic(() ->
882                "[LOOKUP] Loading the default LogFactory implementation '" + FACTORY_DEFAULT +
883                "' via the same class loader that loaded this LogFactory class (ie not looking in the context class loader).");
884            // Note: unlike the above code which can try to load custom LogFactory
885            // implementations via the TCCL, we don't try to load the default LogFactory
886            // implementation via the context class loader because:
887            // * that can cause problems (see comments in newFactory method)
888            // * no-one should be customizing the code of the default class
889            // Yes, we do give up the ability for the child to ship a newer
890            // version of the LogFactoryImpl class and have it used dynamically
891            // by an old LogFactory class in the parent, but that isn't
892            // necessarily a good idea anyway.
893            factory = newFactory(FACTORY_DEFAULT, thisClassLoaderRef.get(), contextClassLoader);
894        }
895        if (factory != null) {
896            /**
897             * Always cache using context class loader.
898             */
899            cacheFactory(contextClassLoader, factory);
900            if (props != null) {
901                final Enumeration<?> names = props.propertyNames();
902                while (names.hasMoreElements()) {
903                    final String name = Objects.toString(names.nextElement(), null);
904                    final String value = props.getProperty(name);
905                    factory.setAttribute(name, value);
906                }
907            }
908        }
909        return factory;
910    }
911
912    /**
913     * Gets a named logger, without the application having to care about factories.
914     *
915     * @param clazz Class from which a log name will be derived
916     * @return a named logger.
917     * @throws LogConfigurationException if a suitable {@code Log} instance cannot be returned
918     */
919    public static Log getLog(final Class<?> clazz) throws LogConfigurationException {
920        return getFactory().getInstance(clazz);
921    }
922
923    /**
924     * Gets a named logger, without the application having to care about factories.
925     *
926     * @param name Logical name of the {@code Log} instance to be returned (the meaning of this name is only known to the underlying logging implementation that
927     *             is being wrapped)
928     * @return a named logger.
929     * @throws LogConfigurationException if a suitable {@code Log} instance cannot be returned
930     */
931    public static Log getLog(final String name) throws LogConfigurationException {
932        return getFactory().getInstance(name);
933    }
934
935    /**
936     * Given a URL that refers to a .properties file, load that file.
937     * This is done under an AccessController so that this method will
938     * succeed when this jarfile is privileged but the caller is not.
939     * This method must therefore remain private to avoid security issues.
940     * <p>
941     * {@code Null} is returned if the URL cannot be opened.
942     * </p>
943     */
944    private static Properties getProperties(final URL url) {
945        return AccessController.doPrivileged((PrivilegedAction<Properties>) () -> {
946            // We must ensure that useCaches is set to false, as the
947            // default behavior of java is to cache file handles, and
948            // this "locks" files, preventing hot-redeploy on windows.
949            try {
950                final URLConnection connection = url.openConnection();
951                connection.setUseCaches(false);
952                try (InputStream stream = connection.getInputStream()) {
953                    if (stream != null) {
954                        final Properties props = new Properties();
955                        props.load(stream);
956                        return props;
957                    }
958                } catch (final IOException e) {
959                    logDiagnostic(() -> "Unable to close stream for URL " + url);
960                }
961            } catch (final IOException e) {
962                logDiagnostic(() -> "Unable to read URL " + url);
963            }
964
965            return null;
966        });
967    }
968
969    /**
970     * Given a file name, return an enumeration of URLs pointing to
971     * all the occurrences of that file name in the classpath.
972     * <p>
973     * This is just like ClassLoader.getResources except that the
974     * operation is done under an AccessController so that this method will
975     * succeed when this jarfile is privileged but the caller is not.
976     * This method must therefore remain private to avoid security issues.
977     * </p>
978     * <p>
979     * If no instances are found, an Enumeration is returned whose
980     * hasMoreElements method returns false (ie an "empty" enumeration).
981     * If resources could not be listed for some reason, null is returned.
982     * </p>
983     */
984    private static Enumeration<URL> getResources(final ClassLoader loader, final String name) {
985        return AccessController.doPrivileged((PrivilegedAction<Enumeration<URL>>) () -> {
986            try {
987                if (loader != null) {
988                    return loader.getResources(name);
989                }
990                return ClassLoader.getSystemResources(name);
991            } catch (final IOException e) {
992                logDiagnostic(() -> "Exception while trying to find configuration file " + name + ":" + e.getMessage());
993                return null;
994            } catch (final NoSuchMethodError e) {
995                // we must be running on a 1.1 JVM which doesn't support
996                // ClassLoader.getSystemResources; just return null in
997                // this case.
998                return null;
999            }
1000        });
1001    }
1002
1003    /**
1004     * Read the specified system property, using an AccessController so that
1005     * the property can be read if JCL has been granted the appropriate
1006     * security rights even if the calling code has not.
1007     * <p>
1008     * Take care not to expose the value returned by this method to the
1009     * calling application in any way; otherwise the calling app can use that
1010     * info to access data that should not be available to it.
1011     * </p>
1012     */
1013    private static String getSystemProperty(final String key, final String def)
1014            throws SecurityException {
1015        return AccessController.doPrivileged((PrivilegedAction<String>) () -> System.getProperty(key, def));
1016    }
1017
1018    /**
1019     * Checks whether the supplied Throwable is one that needs to be
1020     * re-thrown and ignores all others.
1021     *
1022     * The following errors are re-thrown:
1023     * <ul>
1024     *   <li>ThreadDeath</li>
1025     *   <li>VirtualMachineError</li>
1026     * </ul>
1027     *
1028     * @param t the Throwable to check
1029     */
1030    protected static void handleThrowable(final Throwable t) {
1031        if (t instanceof ThreadDeath) {
1032            throw (ThreadDeath) t;
1033        }
1034        if (t instanceof VirtualMachineError) {
1035            throw (VirtualMachineError) t;
1036        }
1037        // All other instances of Throwable will be silently ignored
1038    }
1039
1040    /**
1041     * Determines whether the given class actually implements {@code LogFactory}.
1042     * Diagnostic information is also logged.
1043     * <p>
1044     * <strong>Usage:</strong> to diagnose whether a class loader conflict is the cause
1045     * of incompatibility. The test used is whether the class is assignable from
1046     * the {@code LogFactory} class loaded by the class's class loader.
1047     * @param logFactoryClass {@code Class} which may implement {@code LogFactory}
1048     * @return true if the {@code logFactoryClass} does extend
1049     * {@code LogFactory} when that class is loaded via the same
1050     * class loader that loaded the {@code logFactoryClass}.
1051     * </p>
1052     */
1053    private static boolean implementsLogFactory(final Class<?> logFactoryClass) {
1054        boolean implementsLogFactory = false;
1055        if (logFactoryClass != null) {
1056            try {
1057                final ClassLoader logFactoryClassLoader = logFactoryClass.getClassLoader();
1058                if (logFactoryClassLoader == null) {
1059                    logDiagnostic("[CUSTOM LOG FACTORY] was loaded by the boot class loader");
1060                } else {
1061                    logHierarchy("[CUSTOM LOG FACTORY] ", logFactoryClassLoader);
1062                    final Class<?> factoryFromCustomLoader = Class.forName("org.apache.commons.logging.LogFactory", false, logFactoryClassLoader);
1063                    implementsLogFactory = factoryFromCustomLoader.isAssignableFrom(logFactoryClass);
1064                    final String logFactoryClassName = logFactoryClass.getName();
1065                    if (implementsLogFactory) {
1066                        logDiagnostic(() -> "[CUSTOM LOG FACTORY] " + logFactoryClassName + " implements LogFactory but was loaded by an incompatible class loader.");
1067                    } else {
1068                        logDiagnostic(() -> "[CUSTOM LOG FACTORY] " + logFactoryClassName + " does not implement LogFactory.");
1069                    }
1070                }
1071            } catch (final SecurityException e) {
1072                //
1073                // The application is running within a hostile security environment.
1074                // This will make it very hard to diagnose issues with JCL.
1075                // Consider running less securely whilst debugging this issue.
1076                //
1077                logDiagnostic(
1078                        () -> "[CUSTOM LOG FACTORY] SecurityException caught trying to determine whether the compatibility was caused by a class loader conflict: "
1079                                + e.getMessage());
1080            } catch (final LinkageError e) {
1081                //
1082                // This should be an unusual circumstance.
1083                // LinkageError's usually indicate that a dependent class has incompatibly changed.
1084                // Another possibility may be an exception thrown by an initializer.
1085                // Time for a clean rebuild?
1086                //
1087                logDiagnostic(
1088                        () -> "[CUSTOM LOG FACTORY] LinkageError caught trying to determine whether the compatibility was caused by a class loader conflict: "
1089                                + e.getMessage());
1090            } catch (final ClassNotFoundException e) {
1091                //
1092                // LogFactory cannot be loaded by the class loader which loaded the custom factory implementation.
1093                // The custom implementation is not viable until this is corrected.
1094                // Ensure that the JCL jar and the custom class are available from the same class loader.
1095                // Running with diagnostics on should give information about the class loaders used
1096                // to load the custom factory.
1097                //
1098                logDiagnostic(() -> "[CUSTOM LOG FACTORY] LogFactory class cannot be loaded by the class loader which loaded "
1099                        + "the custom LogFactory implementation. Is the custom factory in the right class loader?");
1100            }
1101        }
1102        return implementsLogFactory;
1103    }
1104
1105    /**
1106     * Tests whether the user wants internal diagnostic output. If so,
1107     * returns an appropriate writer object. Users can enable diagnostic
1108     * output by setting the system property named {@link #DIAGNOSTICS_DEST_PROPERTY} to
1109     * a file name, or the special values STDOUT or STDERR.
1110     */
1111    private static PrintStream initDiagnostics() {
1112        String dest;
1113        try {
1114            dest = getSystemProperty(DIAGNOSTICS_DEST_PROPERTY, null);
1115            if (dest == null) {
1116                return null;
1117            }
1118        } catch (final SecurityException ex) {
1119            // We must be running in some very secure environment.
1120            // We just have to assume output is not wanted.
1121            return null;
1122        }
1123
1124        if (dest.equals("STDOUT")) {
1125            return System.out;
1126        }
1127        if (dest.equals("STDERR")) {
1128            return System.err;
1129        }
1130        try {
1131            // open the file in append mode
1132            final FileOutputStream fos = new FileOutputStream(dest, true);
1133            return new PrintStream(fos, false, StandardCharsets.UTF_8.name());
1134        } catch (final IOException ex) {
1135            // We should report this to the user - but how?
1136            return null;
1137        }
1138    }
1139
1140    private static boolean isClassAvailable(final String className, final ClassLoader classLoader) {
1141        logDiagnostic(() -> "Checking if class '" + className + "' is available in class loader " + objectId(classLoader));
1142        try {
1143            Class.forName(className, true, classLoader);
1144            return true;
1145        } catch (final ClassNotFoundException | LinkageError e) {
1146            logDiagnostic(() -> "Failed to load class '" + className + "' from class loader " + objectId(classLoader) + ": " + e.getMessage());
1147        }
1148        return false;
1149    }
1150
1151    /**
1152     * Tests whether the user enabled internal logging.
1153     * <p>
1154     * By the way, sorry for the incorrect grammar, but calling this method
1155     * areDiagnosticsEnabled just isn't Java beans style.
1156     * </p>
1157     *
1158     * @return true if calls to logDiagnostic will have any effect.
1159     * @since 1.1
1160     */
1161    protected static boolean isDiagnosticsEnabled() {
1162        return DIAGNOSTICS_STREAM != null;
1163    }
1164
1165    /**
1166     * Generates useful diagnostics regarding the class loader tree for
1167     * the specified class.
1168     * <p>
1169     * As an example, if the specified class was loaded via a webapp's
1170     * class loader, then you may get the following output:
1171     * </p>
1172     * <pre>
1173     * Class com.acme.Foo was loaded via class loader 11111
1174     * ClassLoader tree: 11111 -> 22222 (SYSTEM) -> 33333 -> BOOT
1175     * </pre>
1176     * <p>
1177     * This method returns immediately if isDiagnosticsEnabled()
1178     * returns false.
1179     * </p>
1180     *
1181     * @param clazz is the class whose class loader + tree are to be
1182     * output.
1183     */
1184    private static void logClassLoaderEnvironment(final Class<?> clazz) {
1185        if (!isDiagnosticsEnabled()) {
1186            return;
1187        }
1188        try {
1189            // Deliberately use System.getProperty here instead of getSystemProperty; if
1190            // the overall security policy for the calling application forbids access to
1191            // these variables then we do not want to output them to the diagnostic stream.
1192            logDiagnostic("[ENV] Extension directories (java.ext.dir): " + System.getProperty("java.ext.dir"));
1193            logDiagnostic("[ENV] Application classpath (java.class.path): " + System.getProperty("java.class.path"));
1194        } catch (final SecurityException ex) {
1195            logDiagnostic("[ENV] Security setting prevent interrogation of system classpaths.");
1196        }
1197        final String className = clazz.getName();
1198        ClassLoader classLoader;
1199        try {
1200            classLoader = getClassLoader(clazz);
1201        } catch (final SecurityException ex) {
1202            // not much useful diagnostics we can print here!
1203            logDiagnostic("[ENV] Security forbids determining the class loader for " + className);
1204            return;
1205        }
1206        logDiagnostic("[ENV] Class " + className + " was loaded via class loader " + objectId(classLoader));
1207        logHierarchy("[ENV] Ancestry of class loader which loaded " + className + " is ", classLoader);
1208    }
1209
1210    /**
1211     * Writes the specified message to the internal logging destination.
1212     * <p>
1213     * Note that this method is private; concrete subclasses of this class
1214     * should not call it because the diagnosticPrefix string this
1215     * method puts in front of all its messages is LogFactory@....,
1216     * while subclasses should put SomeSubClass@...
1217     * </p>
1218     * <p>
1219     * Subclasses should instead compute their own prefix, then call
1220     * logRawDiagnostic. Note that calling isDiagnosticsEnabled is
1221     * fine for subclasses.
1222     * </p>
1223     * <p>
1224     * Note that it is safe to call this method before initDiagnostics
1225     * is called; any output will just be ignored (as isDiagnosticsEnabled
1226     * will return false).
1227     * </p>
1228     *
1229     * @param msg is the diagnostic message to be output.
1230     */
1231    private static void logDiagnostic(final String msg) {
1232        if (DIAGNOSTICS_STREAM != null) {
1233            logDiagnosticDirect(msg);
1234        }
1235    }
1236
1237    /**
1238     * Writes the specified message to the internal logging destination.
1239     * <p>
1240     * Note that this method is private; concrete subclasses of this class
1241     * should not call it because the diagnosticPrefix string this
1242     * method puts in front of all its messages is LogFactory@....,
1243     * while subclasses should put SomeSubClass@...
1244     * </p>
1245     * <p>
1246     * Subclasses should instead compute their own prefix, then call
1247     * logRawDiagnostic. Note that calling isDiagnosticsEnabled is
1248     * fine for subclasses.
1249     * </p>
1250     * <p>
1251     * Note that it is safe to call this method before initDiagnostics
1252     * is called; any output will just be ignored (as isDiagnosticsEnabled
1253     * will return false).
1254     * </p>
1255     *
1256     * @param msg is the diagnostic message to be output.
1257     */
1258    private static void logDiagnostic(final Supplier<String> msg) {
1259        if (DIAGNOSTICS_STREAM != null) {
1260            logDiagnosticDirect(msg.get());
1261        }
1262    }
1263
1264    private static void logDiagnosticDirect(final String msg) {
1265        DIAGNOSTICS_STREAM.print(DIAGNOSTICS_PREFIX);
1266        DIAGNOSTICS_STREAM.println(msg);
1267        DIAGNOSTICS_STREAM.flush();
1268    }
1269
1270    /**
1271     * Logs diagnostic messages about the given class loader
1272     * and it's hierarchy. The prefix is prepended to the message
1273     * and is intended to make it easier to understand the logs.
1274     * @param prefix
1275     * @param classLoader
1276     */
1277    private static void logHierarchy(final String prefix, ClassLoader classLoader) {
1278        if (!isDiagnosticsEnabled()) {
1279            return;
1280        }
1281        ClassLoader systemClassLoader;
1282        if (classLoader != null) {
1283            logDiagnostic(prefix + objectId(classLoader) + " == '" + classLoader.toString() + "'");
1284        }
1285        try {
1286            systemClassLoader = ClassLoader.getSystemClassLoader();
1287        } catch (final SecurityException ex) {
1288            logDiagnostic(prefix + "Security forbids determining the system class loader.");
1289            return;
1290        }
1291        if (classLoader != null) {
1292            final StringBuilder buf = new StringBuilder(prefix + "ClassLoader tree:");
1293            for(;;) {
1294                buf.append(objectId(classLoader));
1295                if (classLoader == systemClassLoader) {
1296                    buf.append(" (SYSTEM) ");
1297                }
1298                try {
1299                    classLoader = classLoader.getParent();
1300                } catch (final SecurityException ex) {
1301                    buf.append(" --> SECRET");
1302                    break;
1303                }
1304                buf.append(" --> ");
1305                if (classLoader == null) {
1306                    buf.append("BOOT");
1307                    break;
1308                }
1309            }
1310            logDiagnostic(buf.toString());
1311        }
1312    }
1313
1314    /**
1315     * Writes the specified message to the internal logging destination.
1316     *
1317     * @param msg is the diagnostic message to be output.
1318     * @since 1.1
1319     */
1320    protected static final void logRawDiagnostic(final String msg) {
1321        if (DIAGNOSTICS_STREAM != null) {
1322            DIAGNOSTICS_STREAM.println(msg);
1323            DIAGNOSTICS_STREAM.flush();
1324        }
1325    }
1326
1327    /**
1328     * Method provided for backwards compatibility; see newFactory version that
1329     * takes 3 parameters.
1330     * <p>
1331     * This method would only ever be called in some rather odd situation.
1332     * Note that this method is static, so overriding in a subclass doesn't
1333     * have any effect unless this method is called from a method in that
1334     * subclass. However this method only makes sense to use from the
1335     * getFactory method, and as that is almost always invoked via
1336     * LogFactory.getFactory, any custom definition in a subclass would be
1337     * pointless. Only a class with a custom getFactory method, then invoked
1338     * directly via CustomFactoryImpl.getFactory or similar would ever call
1339     * this. Anyway, it's here just in case, though the "managed class loader"
1340     * value output to the diagnostics will not report the correct value.
1341     * </p>
1342     *
1343     * @param factoryClass factory class.
1344     * @param classLoader class loader.
1345     * @return a LogFactory.
1346     */
1347    protected static LogFactory newFactory(final String factoryClass,
1348                                           final ClassLoader classLoader) {
1349        return newFactory(factoryClass, classLoader, null);
1350    }
1351
1352    /**
1353     * Gets a new instance of the specified {@code LogFactory} implementation class, loaded by the specified class loader. If that fails, try the class loader
1354     * used to load this (abstract) LogFactory.
1355     * <p>
1356     * <strong>ClassLoader conflicts</strong>
1357     * </p>
1358     * <p>
1359     * Note that there can be problems if the specified ClassLoader is not the same as the class loader that loaded this class, that is, when loading a concrete
1360     * LogFactory subclass via a context class loader.
1361     * </p>
1362     * <p>
1363     * The problem is the same one that can occur when loading a concrete Log subclass via a context class loader.
1364     * </p>
1365     * <p>
1366     * The problem occurs when code running in the context class loader calls class X which was loaded via a parent class loader, and class X then calls
1367     * LogFactory.getFactory (either directly or via LogFactory.getLog). Because class X was loaded via the parent, it binds to LogFactory loaded via the
1368     * parent. When the code in this method finds some LogFactoryYYYY class in the child (context) class loader, and there also happens to be a LogFactory class
1369     * defined in the child class loader, then LogFactoryYYYY will be bound to LogFactory@childloader. It cannot be cast to LogFactory@parentloader, that is,
1370     * this method cannot return the object as the desired type. Note that it doesn't matter if the LogFactory class in the child class loader is identical to
1371     * the LogFactory class in the parent class loader, they are not compatible.
1372     * </p>
1373     * <p>
1374     * The solution taken here is to simply print out an error message when this occurs then throw an exception. The deployer of the application must ensure
1375     * they remove all occurrences of the LogFactory class from the child class loader in order to resolve the issue. Note that they do not have to move the
1376     * custom LogFactory subclass; that is ok as long as the only LogFactory class it can find to bind to is in the parent class loader.
1377     * </p>
1378     *
1379     * @param factoryClass       Fully qualified name of the {@code LogFactory} implementation class
1380     * @param classLoader        ClassLoader from which to load this class
1381     * @param contextClassLoader is the context that this new factory will manage logging for.
1382     * @return a new instance of the specified {@code LogFactory}.
1383     * @throws LogConfigurationException if a suitable instance cannot be created
1384     * @since 1.1
1385     */
1386    protected static LogFactory newFactory(final String factoryClass,
1387                                           final ClassLoader classLoader,
1388                                           final ClassLoader contextClassLoader)
1389            throws LogConfigurationException {
1390        // Note that any unchecked exceptions thrown by the createFactory
1391        // method will propagate out of this method; in particular a
1392        // ClassCastException can be thrown.
1393        final Object result = AccessController.doPrivileged((PrivilegedAction<?>) () -> createFactory(factoryClass, classLoader));
1394        if (result instanceof LogConfigurationException) {
1395            final LogConfigurationException ex = (LogConfigurationException) result;
1396            logDiagnostic(() -> "An error occurred while loading the factory class:" + ex.getMessage());
1397            throw ex;
1398        }
1399        logDiagnostic(() -> "Created object " + objectId(result) + " to manage class loader " + objectId(contextClassLoader));
1400        return (LogFactory) result;
1401    }
1402
1403    /**
1404     * Tries to load one of the standard three implementations from the given classloader.
1405     * <p>
1406     *     We assume that {@code classLoader} can load this class.
1407     * </p>
1408     * @param classLoader The classloader to use.
1409     * @return An implementation of this class.
1410     */
1411    private static LogFactory newStandardFactory(final ClassLoader classLoader) {
1412        if (isClassAvailable(LOG4J_TO_SLF4J_BRIDGE, classLoader)) {
1413            try {
1414                return (LogFactory) Class.forName(FACTORY_SLF4J, true, classLoader).getConstructor().newInstance();
1415            } catch (final LinkageError | ReflectiveOperationException ignored) {
1416            } finally {
1417                logDiagnostic(() ->
1418                        "[LOOKUP] Log4j API to SLF4J redirection detected. Loading the SLF4J LogFactory implementation '" + FACTORY_SLF4J + "'.");
1419            }
1420        }
1421        try {
1422            return (LogFactory) Class.forName(FACTORY_LOG4J_API, true, classLoader).getConstructor().newInstance();
1423        } catch (final LinkageError | ReflectiveOperationException ignored) {
1424        } finally {
1425            logDiagnostic(() -> "[LOOKUP] Loading the Log4j API LogFactory implementation '" + FACTORY_LOG4J_API + "'.");
1426        }
1427        try {
1428            return (LogFactory) Class.forName(FACTORY_SLF4J, true, classLoader).getConstructor().newInstance();
1429        } catch (final LinkageError | ReflectiveOperationException ignored) {
1430        } finally {
1431            logDiagnostic(() -> "[LOOKUP] Loading the SLF4J LogFactory implementation '" + FACTORY_SLF4J + "'.");
1432        }
1433        try {
1434            return (LogFactory) Class.forName(FACTORY_DEFAULT, true, classLoader).getConstructor().newInstance();
1435        } catch (final LinkageError | ReflectiveOperationException ignored) {
1436        } finally {
1437            logDiagnostic(() -> "[LOOKUP] Loading the legacy LogFactory implementation '" + FACTORY_DEFAULT + "'.");
1438        }
1439        return null;
1440    }
1441
1442    /**
1443     * Returns a string that uniquely identifies the specified object, including
1444     * its class.
1445     * <p>
1446     * The returned string is of form {@code "className@hashCode"}, that is, is the same as
1447     * the return value of the {@link Object#toString()} method, but works even when
1448     * the specified object's class has overridden the toString method.
1449     * </p>
1450     *
1451     * @param obj may be null.
1452     * @return a string of form {@code className@hashCode}, or "null" if obj is null.
1453     * @since 1.1
1454     */
1455    public static String objectId(final Object obj) {
1456        if (obj == null) {
1457            return "null";
1458        }
1459        return obj.getClass().getName() + "@" + System.identityHashCode(obj);
1460    }
1461
1462    /**
1463     * Releases any internal references to previously created {@link LogFactory}
1464     * instances that have been associated with the specified class loader
1465     * (if any), after calling the instance method {@code release()} on
1466     * each of them.
1467     *
1468     * @param classLoader ClassLoader for which to release the LogFactory
1469     */
1470    public static void release(final ClassLoader classLoader) {
1471        logDiagnostic(() -> "Releasing factory for class loader " + objectId(classLoader));
1472        // factories is not final and could be replaced in this block.
1473        final Hashtable<ClassLoader, LogFactory> factories = LogFactory.factories;
1474        synchronized (factories) {
1475            if (classLoader == null) {
1476                if (nullClassLoaderFactory != null) {
1477                    nullClassLoaderFactory.release();
1478                    nullClassLoaderFactory = null;
1479                }
1480            } else {
1481                final LogFactory factory = factories.get(classLoader);
1482                if (factory != null) {
1483                    factory.release();
1484                    factories.remove(classLoader);
1485                }
1486            }
1487        }
1488    }
1489
1490    /**
1491     * Release any internal references to previously created {@link LogFactory}
1492     * instances, after calling the instance method {@code release()} on
1493     * each of them.  This is useful in environments like servlet containers,
1494     * which implement application reloading by throwing away a ClassLoader.
1495     * Dangling references to objects in that class loader would prevent
1496     * garbage collection.
1497     */
1498    public static void releaseAll() {
1499        logDiagnostic("Releasing factory for all class loaders.");
1500        // factories is not final and could be replaced in this block.
1501        final Hashtable<ClassLoader, LogFactory> factories = LogFactory.factories;
1502        synchronized (factories) {
1503            factories.values().forEach(LogFactory::release);
1504            factories.clear();
1505            if (nullClassLoaderFactory != null) {
1506                nullClassLoaderFactory.release();
1507                nullClassLoaderFactory = null;
1508            }
1509        }
1510    }
1511
1512    /** Trims the given string in a null-safe manner. */
1513    private static String trim(final String src) {
1514        return src != null ? src.trim() : null;
1515    }
1516
1517    /**
1518     * Constructs a new instance.
1519     */
1520    protected LogFactory() {
1521    }
1522
1523    /**
1524     * Gets the configuration attribute with the specified name (if any),
1525     * or {@code null} if there is no such attribute.
1526     *
1527     * @param name Name of the attribute to return
1528     * @return the configuration attribute with the specified name.
1529     */
1530    public abstract Object getAttribute(String name);
1531
1532    /**
1533     * Gets an array containing the names of all currently defined configuration attributes. If there are no such attributes, a zero length array is returned.
1534     *
1535     * @return an array containing the names of all currently defined configuration attributes
1536     */
1537    public abstract String[] getAttributeNames();
1538
1539    /**
1540     * Gets a Log for the given class.
1541     *
1542     * @param clazz Class for which a suitable Log name will be derived
1543     * @return a name from the specified class.
1544     * @throws LogConfigurationException if a suitable {@code Log} instance cannot be returned
1545     */
1546    public abstract Log getInstance(Class<?> clazz) throws LogConfigurationException;
1547
1548    /**
1549     * Gets a (possibly new) {@code Log} instance, using the factory's current set of configuration attributes.
1550     * <p>
1551     * <strong>NOTE</strong> - Depending upon the implementation of the {@code LogFactory} you are using, the {@code Log} instance you are returned may or may
1552     * not be local to the current application, and may or may not be returned again on a subsequent call with the same name argument.
1553     * </p>
1554     *
1555     * @param name Logical name of the {@code Log} instance to be returned (the meaning of this name is only known to the underlying logging implementation that
1556     *             is being wrapped)
1557     * @return a {@code Log} instance.
1558     * @throws LogConfigurationException if a suitable {@code Log} instance cannot be returned
1559     */
1560    public abstract Log getInstance(String name)
1561        throws LogConfigurationException;
1562
1563    /**
1564     * Releases any internal references to previously created {@link Log}
1565     * instances returned by this factory.  This is useful in environments
1566     * like servlet containers, which implement application reloading by
1567     * throwing away a ClassLoader.  Dangling references to objects in that
1568     * class loader would prevent garbage collection.
1569     */
1570    public abstract void release();
1571
1572    /**
1573     * Removes any configuration attribute associated with the specified name.
1574     * If there is no such attribute, no action is taken.
1575     *
1576     * @param name Name of the attribute to remove
1577     */
1578    public abstract void removeAttribute(String name);
1579
1580    //
1581    // We can't do this in the class constructor, as there are many
1582    // static methods on this class that can be called before any
1583    // LogFactory instances are created, and they depend upon this
1584    // stuff having been set up.
1585    //
1586    // Note that this block must come after any variable declarations used
1587    // by any methods called from this block, as we want any static initializer
1588    // associated with the variable to run first. If static initializers for
1589    // variables run after this code, then (a) their value might be needed
1590    // by methods called from here, and (b) they might *override* any value
1591    // computed here!
1592    //
1593    // So the wisest thing to do is just to place this code at the very end
1594    // of the class file.
1595
1596    /**
1597     * Sets the configuration attribute with the specified name.  Calling
1598     * this with a {@code null} value is equivalent to calling
1599     * {@code removeAttribute(name)}.
1600     *
1601     * @param name Name of the attribute to set
1602     * @param value Value of the attribute to set, or {@code null}
1603     *  to remove any setting for this attribute
1604     */
1605    public abstract void setAttribute(String name, Object value);
1606
1607}