org.apache.commons.logging.impl

Class LogFactoryImpl


public class LogFactoryImpl
extends LogFactory

Concrete subclass of LogFactory that implements the following algorithm to dynamically select a logging implementation class to instantiate a wrapper for.

If the selected Log implementation class has a setLogFactory() method that accepts a LogFactory parameter, this method will be called on each newly created instance to identify the associated factory. This makes factory configuration attributes available to the Log instance, if it so desires.

This factory will remember previously created Log instances for the same name, and will return them on repeated requests to the getInstance() method.

Version:
$Revision: 581090 $ $Date: 2007-10-02 00:01:06 +0200 (ti, 02 okt 2007) $
Authors:
Rod Waldhoff
Craig R. McClanahan
Richard A. Sitze
Brian Stansberry

Field Summary

static String
ALLOW_FLAWED_CONTEXT_PROPERTY
The name (org.apache.commons.logging.Log.allowFlawedContext) of the system property which can be set true/false to determine system behaviour when a bad context-classloader is encountered.
static String
ALLOW_FLAWED_DISCOVERY_PROPERTY
The name (org.apache.commons.logging.Log.allowFlawedDiscovery) of the system property which can be set true/false to determine system behaviour when a bad logging adapter class is encountered during logging discovery.
static String
ALLOW_FLAWED_HIERARCHY_PROPERTY
The name (org.apache.commons.logging.Log.allowFlawedHierarchy) of the system property which can be set true/false to determine system behaviour when a logging adapter class is encountered which has bound to the wrong Log class implementation.
private static String
LOGGING_IMPL_JDK14_LOGGER
Jdk14Logger class name
private static String
LOGGING_IMPL_LOG4J_LOGGER
Log4JLogger class name
private static String
LOGGING_IMPL_LUMBERJACK_LOGGER
Jdk13LumberjackLogger class name
private static String
LOGGING_IMPL_SIMPLE_LOGGER
SimpleLog class name
static String
LOG_PROPERTY
The name (org.apache.commons.logging.Log) of the system property identifying our Log implementation class.
protected static String
LOG_PROPERTY_OLD
The deprecated system property used for backwards compatibility with old versions of JCL.
private static String
PKG_IMPL
private static int
PKG_LEN
private boolean
allowFlawedContext
See getBaseClassLoader and initConfiguration.
private boolean
allowFlawedDiscovery
See handleFlawedDiscovery and initConfiguration.
private boolean
allowFlawedHierarchy
See handleFlawedHierarchy and initConfiguration.
protected Hashtable
attributes
Configuration attributes.
private static String[]
classesToDiscover
The names of classes that will be tried (in order) as logging adapters.
private String
diagnosticPrefix
The string prefixed to every message output by the logDiagnostic method.
protected Hashtable
instances
The Log instances that have already been created, keyed by logger name.
private String
logClassName
Name of the class implementing the Log interface.
protected Constructor
logConstructor
The one-argument constructor of the Log implementation class that will be used to create new instances.
protected Class[]
logConstructorSignature
The signature of the Constructor to be used.
protected Method
logMethod
The one-argument setLogFactory method of the selected Log method, if it exists.
protected Class[]
logMethodSignature
The signature of the setLogFactory method to be used.
private boolean
useTCCL
Determines whether logging classes should be loaded using the thread-context classloader, or via the classloader that loaded this LogFactoryImpl class.

Fields inherited from class org.apache.commons.logging.LogFactory

DIAGNOSTICS_DEST_PROPERTY, FACTORY_DEFAULT, FACTORY_PROPERTIES, FACTORY_PROPERTY, HASHTABLE_IMPLEMENTATION_PROPERTY, PRIORITY_KEY, SERVICE_ID, TCCL_KEY, WEAK_HASHTABLE_CLASSNAME, diagnosticPrefix, diagnosticsStream, factories, nullClassLoaderFactory, thisClassLoader

Constructor Summary

LogFactoryImpl()
Public no-arguments constructor required by the lookup mechanism.

Method Summary

private Log
createLogFromClass(String logAdapterClassName, String logCategory, boolean affectState)
Attempts to load the given class, find a suitable constructor, and instantiate an instance of Log.
private Log
discoverLogImplementation(String logCategory)
Attempts to create a Log instance for the given category name.
private String
findUserSpecifiedLogClassName()
Checks system properties and the attribute map for a Log implementation specified by the user under the property names LOG_PROPERTY or LOG_PROPERTY_OLD.
Object
getAttribute(String name)
Return the configuration attribute with the specified name (if any), or null if there is no such attribute.
String[]
getAttributeNames()
Return an array containing the names of all currently defined configuration attributes.
private ClassLoader
getBaseClassLoader()
Return the classloader from which we should try to load the logging adapter classes.
private boolean
getBooleanConfiguration(String key, boolean dflt)
Get the setting for the user-configurable behaviour specified by key.
protected static ClassLoader
getClassLoader(Class clazz)
Workaround for bug in Java1.2; in theory this method is not needed.
private String
getConfigurationValue(String property)
Attempt to find an attribute (see method setAttribute) or a system property with the provided name and return its value.
protected static ClassLoader
getContextClassLoader()
Gets the context classloader.
private static ClassLoader
getContextClassLoaderInternal()
Calls LogFactory.directGetContextClassLoader under the control of an AccessController class.
Log
getInstance(Class clazz)
Convenience method to derive a name from the specified class and call getInstance(String) with it.
Log
getInstance(String name)
Construct (if necessary) and return a Log instance, using the factory's current set of configuration attributes.
protected String
getLogClassName()
Deprecated. Never invoked by this class; subclasses should not assume it will be.
protected Constructor
getLogConstructor()
Deprecated. Never invoked by this class; subclasses should not assume it will be.
private ClassLoader
getLowestClassLoader(ClassLoader c1, ClassLoader c2)
Given two related classloaders, return the one which is a child of the other.
private ClassLoader
getParentClassLoader(ClassLoader cl)
Fetch the parent classloader of a specified classloader.
private static String
getSystemProperty(String key, String def)
Read the specified system property, using an AccessController so that the property can be read if JCL has been granted the appropriate security rights even if the calling code has not.
private void
handleFlawedDiscovery(String logAdapterClassName, ClassLoader classLoader, Throwable discoveryFlaw)
Generates an internal diagnostic logging of the discovery failure and then throws a LogConfigurationException that wraps the passed Throwable.
private void
handleFlawedHierarchy(ClassLoader badClassLoader, Class badClass)
Report a problem loading the log adapter, then either return (if the situation is considered recoverable) or throw a LogConfigurationException.
private void
informUponSimilarName(StringBuffer messageBuffer, String name, String candidate)
Appends message if the given name is similar to the candidate.
private void
initConfiguration()
Initialize a number of variables that control the behaviour of this class and that can be tweaked by the user.
private void
initDiagnostics()
Calculate and cache a string that uniquely identifies this instance, including which classloader the object was loaded from.
protected static boolean
isDiagnosticsEnabled()
Workaround for bug in Java1.2; in theory this method is not needed.
protected boolean
isJdk13LumberjackAvailable()
Deprecated. Never invoked by this class; subclasses should not assume it will be.
protected boolean
isJdk14Available()
Deprecated. Never invoked by this class; subclasses should not assume it will be.
protected boolean
isLog4JAvailable()
Deprecated. Never invoked by this class; subclasses should not assume it will be.
private boolean
isLogLibraryAvailable(String name, String classname)
Utility method to check whether a particular logging library is present and available for use.
protected void
logDiagnostic(String msg)
Output a diagnostic message to a user-specified destination (if the user has enabled diagnostic logging).
protected Log
newInstance(String name)
Create and return a new Log instance for the specified name.
void
release()
Release any internal references to previously created Log instances returned by this factory.
void
removeAttribute(String name)
Remove any configuration attribute associated with the specified name.
void
setAttribute(String name, Object value)
Set the configuration attribute with the specified name.

Methods inherited from class org.apache.commons.logging.LogFactory

cacheFactory, createFactory, createFactoryStore, directGetContextClassLoader, getAttribute, getAttributeNames, getCachedFactory, getClassLoader, getConfigurationFile, getContextClassLoader, getContextClassLoaderInternal, getFactory, getInstance, getInstance, getLog, getLog, getProperties, getResourceAsStream, getResources, getSystemProperty, implementsLogFactory, initDiagnostics, isDiagnosticsEnabled, logClassLoaderEnvironment, logDiagnostic, logHierarchy, logRawDiagnostic, newFactory, newFactory, objectId, release, release, releaseAll, removeAttribute, setAttribute, trim

Field Details

ALLOW_FLAWED_CONTEXT_PROPERTY

public static final String ALLOW_FLAWED_CONTEXT_PROPERTY
The name (org.apache.commons.logging.Log.allowFlawedContext) of the system property which can be set true/false to determine system behaviour when a bad context-classloader is encountered. When set to false, a LogConfigurationException is thrown if LogFactoryImpl is loaded via a child classloader of the TCCL (this should never happen in sane systems). Default behaviour: true (tolerates bad context classloaders) See also method setAttribute.

ALLOW_FLAWED_DISCOVERY_PROPERTY

public static final String ALLOW_FLAWED_DISCOVERY_PROPERTY
The name (org.apache.commons.logging.Log.allowFlawedDiscovery) of the system property which can be set true/false to determine system behaviour when a bad logging adapter class is encountered during logging discovery. When set to false, an exception will be thrown and the app will fail to start. When set to true, discovery will continue (though the user might end up with a different logging implementation than they expected). Default behaviour: true (tolerates bad logging adapters) See also method setAttribute.

ALLOW_FLAWED_HIERARCHY_PROPERTY

public static final String ALLOW_FLAWED_HIERARCHY_PROPERTY
The name (org.apache.commons.logging.Log.allowFlawedHierarchy) of the system property which can be set true/false to determine system behaviour when a logging adapter class is encountered which has bound to the wrong Log class implementation. When set to false, an exception will be thrown and the app will fail to start. When set to true, discovery will continue (though the user might end up with a different logging implementation than they expected). Default behaviour: true (tolerates bad Log class hierarchy) See also method setAttribute.

LOGGING_IMPL_JDK14_LOGGER

private static final String LOGGING_IMPL_JDK14_LOGGER
Jdk14Logger class name

LOGGING_IMPL_LOG4J_LOGGER

private static final String LOGGING_IMPL_LOG4J_LOGGER
Log4JLogger class name

LOGGING_IMPL_LUMBERJACK_LOGGER

private static final String LOGGING_IMPL_LUMBERJACK_LOGGER
Jdk13LumberjackLogger class name

LOGGING_IMPL_SIMPLE_LOGGER

private static final String LOGGING_IMPL_SIMPLE_LOGGER
SimpleLog class name

LOG_PROPERTY

public static final String LOG_PROPERTY

LOG_PROPERTY_OLD

protected static final String LOG_PROPERTY_OLD
The deprecated system property used for backwards compatibility with old versions of JCL.

PKG_IMPL

private static final String PKG_IMPL

PKG_LEN

private static final int PKG_LEN

allowFlawedContext

private boolean allowFlawedContext
See getBaseClassLoader and initConfiguration.

allowFlawedDiscovery

private boolean allowFlawedDiscovery
See handleFlawedDiscovery and initConfiguration.

allowFlawedHierarchy

private boolean allowFlawedHierarchy
See handleFlawedHierarchy and initConfiguration.

attributes

protected Hashtable attributes
Configuration attributes.

classesToDiscover

private static final String[] classesToDiscover
The names of classes that will be tried (in order) as logging adapters. Each class is expected to implement the Log interface, and to throw NoClassDefFound or ExceptionInInitializerError when loaded if the underlying logging library is not available. Any other error indicates that the underlying logging library is available but broken/unusable for some reason.

diagnosticPrefix

private String diagnosticPrefix
The string prefixed to every message output by the logDiagnostic method.

instances

protected Hashtable instances
The Log instances that have already been created, keyed by logger name.

logClassName

private String logClassName
Name of the class implementing the Log interface.

logConstructor

protected Constructor logConstructor
The one-argument constructor of the Log implementation class that will be used to create new instances. This value is initialized by getLogConstructor(), and then returned repeatedly.

logConstructorSignature

protected Class[] logConstructorSignature
The signature of the Constructor to be used.

logMethod

protected Method logMethod

logMethodSignature

protected Class[] logMethodSignature
The signature of the setLogFactory method to be used.

useTCCL

private boolean useTCCL
Determines whether logging classes should be loaded using the thread-context classloader, or via the classloader that loaded this LogFactoryImpl class.

Constructor Details

LogFactoryImpl

public LogFactoryImpl()
Public no-arguments constructor required by the lookup mechanism.

Method Details

createLogFromClass

private Log createLogFromClass(String logAdapterClassName,
                               String logCategory,
                               boolean affectState)
            throws LogConfigurationException
Attempts to load the given class, find a suitable constructor, and instantiate an instance of Log.
Parameters:
logAdapterClassName - classname of the Log implementation
logCategory - argument to pass to the Log implementation's constructor
affectState - true if this object's state should be affected by this method call, false otherwise.
Returns:
an instance of the given class, or null if the logging library associated with the specified adapter is not available.
Throws:
LogConfigurationException - if there was a serious error with configuration and the handleFlawedDiscovery method decided this problem was fatal.

discoverLogImplementation

private Log discoverLogImplementation(String logCategory)
            throws LogConfigurationException
Attempts to create a Log instance for the given category name. Follows the discovery process described in the class javadoc.
Parameters:
logCategory - the name of the log category
Throws:
LogConfigurationException - if an error in discovery occurs, or if no adapter at all can be instantiated

findUserSpecifiedLogClassName

private String findUserSpecifiedLogClassName()
Returns:
classname specified by the user, or null

getAttribute

public Object getAttribute(String name)
Return the configuration attribute with the specified name (if any), or null if there is no such attribute.
Overrides:
getAttribute in interface LogFactory
Parameters:
name - Name of the attribute to return

getAttributeNames

public String[] getAttributeNames()
Return an array containing the names of all currently defined configuration attributes. If there are no such attributes, a zero length array is returned.
Overrides:
getAttributeNames in interface LogFactory

getBaseClassLoader

private ClassLoader getBaseClassLoader()
            throws LogConfigurationException
Return the classloader from which we should try to load the logging adapter classes.

This method usually returns the context classloader. However if it is discovered that the classloader which loaded this class is a child of the context classloader and the allowFlawedContext option has been set then the classloader which loaded this class is returned instead.

The only time when the classloader which loaded this class is a descendant (rather than the same as or an ancestor of the context classloader) is when an app has created custom classloaders but failed to correctly set the context classloader. This is a bug in the calling application; however we provide the option for JCL to simply generate a warning rather than fail outright.


getBooleanConfiguration

private boolean getBooleanConfiguration(String key,
                                        boolean dflt)
Get the setting for the user-configurable behaviour specified by key. If nothing has explicitly been set, then return dflt.

getClassLoader

protected static ClassLoader getClassLoader(Class clazz)
Workaround for bug in Java1.2; in theory this method is not needed. See LogFactory.getClassLoader.
Overrides:
getClassLoader in interface LogFactory
Since:
1.1

getConfigurationValue

private String getConfigurationValue(String property)
Attempt to find an attribute (see method setAttribute) or a system property with the provided name and return its value.

The attributes associated with this object are checked before system properties in case someone has explicitly called setAttribute, or a configuration property has been set in a commons-logging.properties file.

Returns:
the value associated with the property, or null.

getContextClassLoader

protected static ClassLoader getContextClassLoader()
            throws LogConfigurationException
Gets the context classloader. This method is a workaround for a java 1.2 compiler bug.
Overrides:
getContextClassLoader in interface LogFactory
Since:
1.1

getContextClassLoaderInternal

private static ClassLoader getContextClassLoaderInternal()
            throws LogConfigurationException
Calls LogFactory.directGetContextClassLoader under the control of an AccessController class. This means that java code running under a security manager that forbids access to ClassLoaders will still work if this class is given appropriate privileges, even when the caller doesn't have such privileges. Without using an AccessController, the the entire call stack must have the privilege before the call is allowed.
Overrides:
getContextClassLoaderInternal in interface LogFactory
Returns:
the context classloader associated with the current thread, or null if security doesn't allow it.
Throws:
LogConfigurationException - if there was some weird error while attempting to get the context classloader.

getInstance

public Log getInstance(Class clazz)
            throws LogConfigurationException
Convenience method to derive a name from the specified class and call getInstance(String) with it.
Overrides:
getInstance in interface LogFactory
Parameters:
clazz - Class for which a suitable Log name will be derived
Throws:
LogConfigurationException - if a suitable Log instance cannot be returned

getInstance

public Log getInstance(String name)
            throws LogConfigurationException
Construct (if necessary) and return a Log instance, using the factory's current set of configuration attributes.

NOTE - Depending upon the implementation of the LogFactory you are using, the Log instance you are returned may or may not be local to the current application, and may or may not be returned again on a subsequent call with the same name argument.

Overrides:
getInstance in interface LogFactory
Parameters:
name - Logical name of the Log instance to be returned (the meaning of this name is only known to the underlying logging implementation that is being wrapped)
Throws:
LogConfigurationException - if a suitable Log instance cannot be returned

getLogClassName

protected String getLogClassName()

Deprecated. Never invoked by this class; subclasses should not assume it will be.


getLogConstructor

protected Constructor getLogConstructor()
            throws LogConfigurationException

Deprecated. Never invoked by this class; subclasses should not assume it will be.

Return the Constructor that can be called to instantiate new Log instances.

IMPLEMENTATION NOTE - Race conditions caused by calling this method from more than one thread are ignored, because the same Constructor instance will ultimately be derived in all circumstances.

Throws:
LogConfigurationException - if a suitable constructor cannot be returned

getLowestClassLoader

private ClassLoader getLowestClassLoader(ClassLoader c1,
                                         ClassLoader c2)
Given two related classloaders, return the one which is a child of the other.

Parameters:
c1 - is a classloader (including the null classloader)
c2 - is a classloader (including the null classloader)
Returns:
c1 if it has c2 as an ancestor, c2 if it has c1 as an ancestor, and null if neither is an ancestor of the other.

getParentClassLoader

private ClassLoader getParentClassLoader(ClassLoader cl)
Fetch the parent classloader of a specified classloader.

If a SecurityException occurs, null is returned.

Note that this method is non-static merely so logDiagnostic is available.


getSystemProperty

private static String getSystemProperty(String key,
                                        String def)
            throws SecurityException
Read the specified system property, using an AccessController so that the property can be read if JCL has been granted the appropriate security rights even if the calling code has not.

Take care not to expose the value returned by this method to the calling application in any way; otherwise the calling app can use that info to access data that should not be available to it.

Overrides:
getSystemProperty in interface LogFactory

handleFlawedDiscovery

private void handleFlawedDiscovery(String logAdapterClassName,
                                   ClassLoader classLoader,
                                   Throwable discoveryFlaw)
Generates an internal diagnostic logging of the discovery failure and then throws a LogConfigurationException that wraps the passed Throwable.
Parameters:
logAdapterClassName - is the class name of the Log implementation that could not be instantiated. Cannot be null.
classLoader - is the classloader that we were trying to load the logAdapterClassName from when the exception occurred.
discoveryFlaw - is the Throwable created by the classloader

handleFlawedHierarchy

private void handleFlawedHierarchy(ClassLoader badClassLoader,
                                   Class badClass)
            throws LogConfigurationException
Report a problem loading the log adapter, then either return (if the situation is considered recoverable) or throw a LogConfigurationException.

There are two possible reasons why we successfully loaded the specified log adapter class then failed to cast it to a Log object:

  1. the specific class just doesn't implement the Log interface (user screwed up), or
  2. the specified class has bound to a Log class loaded by some other classloader; Log@classloaderX cannot be cast to Log@classloaderY.

Here we try to figure out which case has occurred so we can give the user some reasonable feedback.

Parameters:
badClassLoader - is the classloader we loaded the problem class from, ie it is equivalent to badClass.getClassLoader().
badClass - is a Class object with the desired name, but which does not implement Log correctly.
Throws:
LogConfigurationException - when the situation should not be recovered from.

informUponSimilarName

private void informUponSimilarName(StringBuffer messageBuffer,
                                   String name,
                                   String candidate)
Appends message if the given name is similar to the candidate.
Parameters:
messageBuffer - StringBuffer the message should be appended to, not null
name - the (trimmed) name to be test against the candidate, not null
candidate - the candidate name (not null)

initConfiguration

private void initConfiguration()
Initialize a number of variables that control the behaviour of this class and that can be tweaked by the user. This is done when the first logger is created, not in the constructor of this class, because we need to give the user a chance to call method setAttribute in order to configure this object.

initDiagnostics

private void initDiagnostics()
Calculate and cache a string that uniquely identifies this instance, including which classloader the object was loaded from.

This string will later be prefixed to each "internal logging" message emitted, so that users can clearly see any unexpected behaviour.

Note that this method does not detect whether internal logging is enabled or not, nor where to output stuff if it is; that is all handled by the parent LogFactory class. This method just computes its own unique prefix for log messages.

Overrides:
initDiagnostics in interface LogFactory

isDiagnosticsEnabled

protected static boolean isDiagnosticsEnabled()
Workaround for bug in Java1.2; in theory this method is not needed. See LogFactory.isDiagnosticsEnabled.
Overrides:
isDiagnosticsEnabled in interface LogFactory

isJdk13LumberjackAvailable

protected boolean isJdk13LumberjackAvailable()

Deprecated. Never invoked by this class; subclasses should not assume it will be.

Is JDK 1.3 with Lumberjack logging available?

isJdk14Available

protected boolean isJdk14Available()

Deprecated. Never invoked by this class; subclasses should not assume it will be.

Return true if JDK 1.4 or later logging is available. Also checks that the Throwable class supports getStackTrace(), which is required by Jdk14Logger.

isLog4JAvailable

protected boolean isLog4JAvailable()

Deprecated. Never invoked by this class; subclasses should not assume it will be.

Is a Log4J implementation available?

isLogLibraryAvailable

private boolean isLogLibraryAvailable(String name,
                                      String classname)
Utility method to check whether a particular logging library is present and available for use. Note that this does not affect the future behaviour of this class.

logDiagnostic

protected void logDiagnostic(String msg)
Output a diagnostic message to a user-specified destination (if the user has enabled diagnostic logging).
Overrides:
logDiagnostic in interface LogFactory
Parameters:
msg - diagnostic message
Since:
1.1

newInstance

protected Log newInstance(String name)
            throws LogConfigurationException
Create and return a new Log instance for the specified name.
Parameters:
name - Name of the new logger
Throws:
LogConfigurationException - if a new instance cannot be created

release

public void release()
Release any internal references to previously created Log instances returned by this factory. This is useful in environments like servlet containers, which implement application reloading by throwing away a ClassLoader. Dangling references to objects in that class loader would prevent garbage collection.
Overrides:
release in interface LogFactory

removeAttribute

public void removeAttribute(String name)
Remove any configuration attribute associated with the specified name. If there is no such attribute, no action is taken.
Overrides:
removeAttribute in interface LogFactory
Parameters:
name - Name of the attribute to remove

setAttribute

public void setAttribute(String name,
                         Object value)
Set the configuration attribute with the specified name. Calling this with a null value is equivalent to calling removeAttribute(name).

This method can be used to set logging configuration programmatically rather than via system properties. It can also be used in code running within a container (such as a webapp) to configure behaviour on a per-component level instead of globally as system properties would do. To use this method instead of a system property, call

 LogFactory.getFactory().setAttribute(...)
 
This must be done before the first Log object is created; configuration changes after that point will be ignored.

This method is also called automatically if LogFactory detects a commons-logging.properties file; every entry in that file is set automatically as an attribute here.

Overrides:
setAttribute in interface LogFactory
Parameters:
name - Name of the attribute to set
value - Value of the attribute to set, or null to remove any setting for this attribute

Copyright 2002-2004 The Apache Software Foundation.