[jboss-cvs] apache/commons-logging/src/java/org/apache/commons/logging/impl ...
Scott Stark
scott.stark at jboss.com
Fri Feb 9 01:57:15 EST 2007
User: starksm
Date: 07/02/09 01:57:15
Modified: commons-logging/src/java/org/apache/commons/logging/impl
package.html NoOpLog.java LogFactoryImpl.java
AvalonLogger.java SimpleLog.java
Jdk13LumberjackLogger.java Log4JLogger.java
Jdk14Logger.java LogKitLogger.java
Added: commons-logging/src/java/org/apache/commons/logging/impl
WeakHashtable.java ServletContextCleaner.java
Log:
Update to the http://apache.ziply.com/jakarta/commons/logging/source/commons-logging-1.1-src.zip release
Revision Changes Path
1.2 +21 -21 apache/commons-logging/src/java/org/apache/commons/logging/impl/package.html
(In the diff below, changes in quantity of whitespace are not shown.)
Index: package.html
===================================================================
RCS file: /cvsroot/jboss/apache/commons-logging/src/java/org/apache/commons/logging/impl/package.html,v
retrieving revision 1.1
retrieving revision 1.2
diff -u -b -r1.1 -r1.2
1.2 +106 -106 apache/commons-logging/src/java/org/apache/commons/logging/impl/NoOpLog.java
(In the diff below, changes in quantity of whitespace are not shown.)
Index: NoOpLog.java
===================================================================
RCS file: /cvsroot/jboss/apache/commons-logging/src/java/org/apache/commons/logging/impl/NoOpLog.java,v
retrieving revision 1.1
retrieving revision 1.2
diff -u -b -r1.1 -r1.2
--- NoOpLog.java 17 Apr 2006 21:00:05 -0000 1.1
+++ NoOpLog.java 9 Feb 2007 06:57:15 -0000 1.2
@@ -28,7 +28,7 @@
*
* @author <a href="mailto:sanders at apache.org">Scott Sanders</a>
* @author Rod Waldhoff
- * @version $Id: NoOpLog.java,v 1.1 2006/04/17 21:00:05 starksm Exp $
+ * @version $Id: NoOpLog.java,v 1.2 2007/02/09 06:57:15 starksm Exp $
*/
public class NoOpLog implements Log, Serializable {
1.2 +1400 -549 apache/commons-logging/src/java/org/apache/commons/logging/impl/LogFactoryImpl.java
(In the diff below, changes in quantity of whitespace are not shown.)
Index: LogFactoryImpl.java
===================================================================
RCS file: /cvsroot/jboss/apache/commons-logging/src/java/org/apache/commons/logging/impl/LogFactoryImpl.java,v
retrieving revision 1.1
retrieving revision 1.2
diff -u -b -r1.1 -r1.2
--- LogFactoryImpl.java 17 Apr 2006 21:00:05 -0000 1.1
+++ LogFactoryImpl.java 9 Feb 2007 06:57:15 -0000 1.2
@@ -20,8 +20,7 @@
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
-import java.security.AccessController;
-import java.security.PrivilegedAction;
+import java.net.URL;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Vector;
@@ -57,25 +56,43 @@
*
* <p>This factory will remember previously created <code>Log</code> instances
* for the same name, and will return them on repeated requests to the
- * <code>getInstance()</code> method. This implementation ignores any
- * configured attributes.</p>
+ * <code>getInstance()</code> method.</p>
*
* @author Rod Waldhoff
* @author Craig R. McClanahan
* @author Richard A. Sitze
- * @version $Revision: 1.1 $ $Date: 2006/04/17 21:00:05 $
+ * @author Brian Stansberry
+ * @version $Revision: 1.2 $ $Date: 2007/02/09 06:57:15 $
*/
public class LogFactoryImpl extends LogFactory {
+
+ /** Log4JLogger class name */
+ private static final String LOGGING_IMPL_LOG4J_LOGGER = "org.apache.commons.logging.impl.Log4JLogger";
+ /** Jdk14Logger class name */
+ private static final String LOGGING_IMPL_JDK14_LOGGER = "org.apache.commons.logging.impl.Jdk14Logger";
+ /** Jdk13LumberjackLogger class name */
+ private static final String LOGGING_IMPL_LUMBERJACK_LOGGER = "org.apache.commons.logging.impl.Jdk13LumberjackLogger";
+ /** SimpleLog class name */
+ private static final String LOGGING_IMPL_SIMPLE_LOGGER = "org.apache.commons.logging.impl.SimpleLog";
+
+ private static final String PKG_IMPL="org.apache.commons.logging.impl.";
+ private static final int PKG_LEN = PKG_IMPL.length();
+
// ----------------------------------------------------------- Constructors
+
/**
* Public no-arguments constructor required by the lookup mechanism.
*/
public LogFactoryImpl() {
super();
+ initDiagnostics(); // method on this object
+ if (isDiagnosticsEnabled()) {
+ logDiagnostic("Instance created.");
+ }
}
@@ -83,8 +100,8 @@
/**
- * The name of the system property identifying our {@link Log}
- * implementation class.
+ * The name (<code>org.apache.commons.logging.Log</code>) of the system
+ * property identifying our {@link Log} implementation class.
*/
public static final String LOG_PROPERTY =
"org.apache.commons.logging.Log";
@@ -92,21 +109,88 @@
/**
* The deprecated system property used for backwards compatibility with
- * the old {@link org.apache.commons.logging.LogSource} class.
+ * old versions of JCL.
*/
protected static final String LOG_PROPERTY_OLD =
"org.apache.commons.logging.log";
+ /**
+ * The name (<code>org.apache.commons.logging.Log.allowFlawedContext</code>)
+ * 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.
+ */
+ public static final String ALLOW_FLAWED_CONTEXT_PROPERTY =
+ "org.apache.commons.logging.Log.allowFlawedContext";
+
+ /**
+ * The name (<code>org.apache.commons.logging.Log.allowFlawedDiscovery</code>)
+ * 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.
+ */
+ public static final String ALLOW_FLAWED_DISCOVERY_PROPERTY =
+ "org.apache.commons.logging.Log.allowFlawedDiscovery";
/**
- * <p>The name of the {@link Log} interface class.</p>
+ * The name (<code>org.apache.commons.logging.Log.allowFlawedHierarchy</code>)
+ * 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.
*/
- private static final String LOG_INTERFACE =
- "org.apache.commons.logging.Log";
+ public static final String ALLOW_FLAWED_HIERARCHY_PROPERTY =
+ "org.apache.commons.logging.Log.allowFlawedHierarchy";
+
+
+ /**
+ * 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.
+ */
+ private static final String[] classesToDiscover = {
+ LOGGING_IMPL_LOG4J_LOGGER,
+ "org.apache.commons.logging.impl.Jdk14Logger",
+ "org.apache.commons.logging.impl.Jdk13LumberjackLogger",
+ "org.apache.commons.logging.impl.SimpleLog"
+ };
// ----------------------------------------------------- Instance Variables
+ /**
+ * Determines whether logging classes should be loaded using the thread-context
+ * classloader, or via the classloader that loaded this LogFactoryImpl class.
+ */
+ private boolean useTCCL = true;
+
+ /**
+ * The string prefixed to every message output by the logDiagnostic method.
+ */
+ private String diagnosticPrefix;
+
/**
* Configuration attributes.
@@ -157,6 +241,20 @@
protected Class logMethodSignature[] =
{ LogFactory.class };
+ /**
+ * See getBaseClassLoader and initConfiguration.
+ */
+ private boolean allowFlawedContext;
+
+ /**
+ * See handleFlawedDiscovery and initConfiguration.
+ */
+ private boolean allowFlawedDiscovery;
+
+ /**
+ * See handleFlawedHierarchy and initConfiguration.
+ */
+ private boolean allowFlawedHierarchy;
// --------------------------------------------------------- Public Methods
@@ -250,6 +348,7 @@
*/
public void release() {
+ logDiagnostic("Releasing all known loggers");
instances.clear();
}
@@ -271,6 +370,21 @@
* Set the configuration attribute with the specified name. Calling
* this with a <code>null</code> value is equivalent to calling
* <code>removeAttribute(name)</code>.
+ * <p>
+ * 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
+ * <pre>
+ * LogFactory.getFactory().setAttribute(...)
+ * </pre>
+ * This must be done before the first Log object is created; configuration
+ * changes after that point will be ignored.
+ * <p>
+ * 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.
*
* @param name Name of the attribute to set
* @param value Value of the attribute to set, or <code>null</code>
@@ -278,70 +392,126 @@
*/
public void setAttribute(String name, Object value) {
+ if (logConstructor != null) {
+ logDiagnostic("setAttribute: call too late; configuration already performed.");
+ }
+
if (value == null) {
attributes.remove(name);
} else {
attributes.put(name, value);
}
+ if (name.equals(TCCL_KEY)) {
+ useTCCL = Boolean.valueOf(value.toString()).booleanValue();
}
-
- // ------------------------------------------------------ Protected Methods
+ }
+ // ------------------------------------------------------
+ // Static Methods
+ //
+ // These methods only defined as workarounds for a java 1.2 bug;
+ // theoretically none of these are needed.
+ // ------------------------------------------------------
/**
- * Return the fully qualified Java classname of the {@link Log}
- * implementation we will be using.
+ * Gets the context classloader.
+ * This method is a workaround for a java 1.2 compiler bug.
+ * @since 1.1
*/
- protected String getLogClassName() {
-
- // Return the previously identified class name (if any)
- if (logClassName != null) {
- return logClassName;
+ protected static ClassLoader getContextClassLoader() throws LogConfigurationException {
+ return LogFactory.getContextClassLoader();
}
- logClassName = (String) getAttribute(LOG_PROPERTY);
- if (logClassName == null) { // @deprecated
- logClassName = (String) getAttribute(LOG_PROPERTY_OLD);
+ /**
+ * Workaround for bug in Java1.2; in theory this method is not needed.
+ * See LogFactory.isDiagnosticsEnabled.
+ */
+ protected static boolean isDiagnosticsEnabled() {
+ return LogFactory.isDiagnosticsEnabled();
}
- if (logClassName == null) {
- try {
- logClassName = System.getProperty(LOG_PROPERTY);
- } catch (SecurityException e) {
- ;
- }
+
+ /**
+ * Workaround for bug in Java1.2; in theory this method is not needed.
+ * See LogFactory.getClassLoader.
+ * @since 1.1
+ */
+ protected static ClassLoader getClassLoader(Class clazz) {
+ return LogFactory.getClassLoader(clazz);
}
- if (logClassName == null) { // @deprecated
+
+ // ------------------------------------------------------ Protected Methods
+
+ /**
+ * Calculate and cache a string that uniquely identifies this instance,
+ * including which classloader the object was loaded from.
+ * <p>
+ * This string will later be prefixed to each "internal logging" message
+ * emitted, so that users can clearly see any unexpected behaviour.
+ * <p>
+ * 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.
+ */
+ private void initDiagnostics() {
+ // It would be nice to include an identifier of the context classloader
+ // that this LogFactoryImpl object is responsible for. However that
+ // isn't possible as that information isn't available. It is possible
+ // to figure this out by looking at the logging from LogFactory to
+ // see the context & impl ids from when this object was instantiated,
+ // in order to link the impl id output as this object's prefix back to
+ // the context it is intended to manage.
+ // Note that this prefix should be kept consistent with that
+ // in LogFactory.
+ Class clazz = this.getClass();
+ ClassLoader classLoader = getClassLoader(clazz);
+ String classLoaderName;
try {
- logClassName = System.getProperty(LOG_PROPERTY_OLD);
- } catch (SecurityException e) {
- ;
+ if (classLoader == null) {
+ classLoaderName = "BOOTLOADER";
+ } else {
+ classLoaderName = objectId(classLoader);
}
+ } catch(SecurityException e) {
+ classLoaderName = "UNKNOWN";
}
-
- if ((logClassName == null) && isLog4JAvailable()) {
- logClassName = "org.apache.commons.logging.impl.Log4JLogger";
+ diagnosticPrefix = "[LogFactoryImpl@" + System.identityHashCode(this) + " from " + classLoaderName + "] ";
}
- if ((logClassName == null) && isJdk14Available()) {
- logClassName = "org.apache.commons.logging.impl.Jdk14Logger";
- }
- if ((logClassName == null) && isJdk13LumberjackAvailable()) {
- logClassName = "org.apache.commons.logging.impl.Jdk13LumberjackLogger";
+ /**
+ * Output a diagnostic message to a user-specified destination (if the
+ * user has enabled diagnostic logging).
+ *
+ * @param msg diagnostic message
+ * @since 1.1
+ */
+ protected void logDiagnostic(String msg) {
+ if (isDiagnosticsEnabled()) {
+ logRawDiagnostic(diagnosticPrefix + msg);
+ }
}
+ /**
+ * Return the fully qualified Java classname of the {@link Log}
+ * implementation we will be using.
+ *
+ * @deprecated Never invoked by this class; subclasses should not assume
+ * it will be.
+ */
+ protected String getLogClassName() {
+
if (logClassName == null) {
- logClassName = "org.apache.commons.logging.impl.SimpleLog";
+ discoverLogImplementation(getClass().getName());
}
- return (logClassName);
-
+ return logClassName;
}
@@ -356,194 +526,875 @@
*
* @exception LogConfigurationException if a suitable constructor
* cannot be returned
+ *
+ * @deprecated Never invoked by this class; subclasses should not assume
+ * it will be.
*/
protected Constructor getLogConstructor()
throws LogConfigurationException {
// Return the previously identified Constructor (if any)
- if (logConstructor != null) {
+ if (logConstructor == null) {
+ discoverLogImplementation(getClass().getName());
+ }
+
return logConstructor;
}
- String logClassName = getLogClassName();
- // Attempt to load the Log implementation class
- Class logClass = null;
- Class logInterface = null;
- try {
- logInterface = this.getClass().getClassLoader().loadClass
- (LOG_INTERFACE);
- logClass = loadClass(logClassName);
- if (logClass == null) {
- throw new LogConfigurationException
- ("No suitable Log implementation for " + logClassName);
+ /**
+ * Is <em>JDK 1.3 with Lumberjack</em> logging available?
+ *
+ * @deprecated Never invoked by this class; subclasses should not assume
+ * it will be.
+ */
+ protected boolean isJdk13LumberjackAvailable() {
+ return isLogLibraryAvailable(
+ "Jdk13Lumberjack",
+ "org.apache.commons.logging.impl.Jdk13LumberjackLogger");
}
- if (!logInterface.isAssignableFrom(logClass)) {
- Class interfaces[] = logClass.getInterfaces();
- for (int i = 0; i < interfaces.length; i++) {
- if (LOG_INTERFACE.equals(interfaces[i].getName())) {
- throw new LogConfigurationException
- ("Invalid class loader hierarchy. " +
- "You have more than one version of '" +
- LOG_INTERFACE + "' visible, which is " +
- "not allowed.");
+
+
+ /**
+ * <p>Return <code>true</code> if <em>JDK 1.4 or later</em> logging
+ * is available. Also checks that the <code>Throwable</code> class
+ * supports <code>getStackTrace()</code>, which is required by
+ * Jdk14Logger.</p>
+ *
+ * @deprecated Never invoked by this class; subclasses should not assume
+ * it will be.
+ */
+ protected boolean isJdk14Available() {
+ return isLogLibraryAvailable(
+ "Jdk14",
+ "org.apache.commons.logging.impl.Jdk14Logger");
}
+
+
+ /**
+ * Is a <em>Log4J</em> implementation available?
+ *
+ * @deprecated Never invoked by this class; subclasses should not assume
+ * it will be.
+ */
+ protected boolean isLog4JAvailable() {
+ return isLogLibraryAvailable(
+ "Log4J",
+ LOGGING_IMPL_LOG4J_LOGGER);
}
- throw new LogConfigurationException
- ("Class " + logClassName + " does not implement '" +
- LOG_INTERFACE + "'.");
+
+
+ /**
+ * Create and return a new {@link org.apache.commons.logging.Log}
+ * instance for the specified name.
+ *
+ * @param name Name of the new logger
+ *
+ * @exception LogConfigurationException if a new instance cannot
+ * be created
+ */
+ protected Log newInstance(String name) throws LogConfigurationException {
+
+ Log instance = null;
+ try {
+ if (logConstructor == null) {
+ instance = discoverLogImplementation(name);
+ }
+ else {
+ Object params[] = { name };
+ instance = (Log) logConstructor.newInstance(params);
+ }
+
+ if (logMethod != null) {
+ Object params[] = { this };
+ logMethod.invoke(instance, params);
+ }
+
+ return (instance);
+
+ } catch (LogConfigurationException lce) {
+
+ // this type of exception means there was a problem in discovery
+ // and we've already output diagnostics about the issue, etc.;
+ // just pass it on
+ throw (LogConfigurationException) lce;
+
+ } catch (InvocationTargetException e) {
+ // A problem occurred invoking the Constructor or Method
+ // previously discovered
+ Throwable c = e.getTargetException();
+ if (c != null) {
+ throw new LogConfigurationException(c);
+ } else {
+ throw new LogConfigurationException(e);
}
} catch (Throwable t) {
+ // A problem occurred invoking the Constructor or Method
+ // previously discovered
throw new LogConfigurationException(t);
}
+ }
- // Identify the <code>setLogFactory</code> method (if there is one)
+
+ // ------------------------------------------------------ Private Methods
+
+ /**
+ * Utility method to check whether a particular logging library is
+ * present and available for use. Note that this does <i>not</i>
+ * affect the future behaviour of this class.
+ */
+ private boolean isLogLibraryAvailable(String name, String classname) {
+ if (isDiagnosticsEnabled()) {
+ logDiagnostic("Checking for '" + name + "'.");
+ }
try {
- logMethod = logClass.getMethod("setLogFactory",
- logMethodSignature);
- } catch (Throwable t) {
- logMethod = null;
+ Log log = createLogFromClass(
+ classname,
+ this.getClass().getName(), // dummy category
+ false);
+
+ if (log == null) {
+ if (isDiagnosticsEnabled()) {
+ logDiagnostic("Did not find '" + name + "'.");
+ }
+ return false;
+ } else {
+ if (isDiagnosticsEnabled()) {
+ logDiagnostic("Found '" + name + "'.");
+ }
+ return true;
+ }
+ } catch(LogConfigurationException e) {
+ if (isDiagnosticsEnabled()) {
+ logDiagnostic("Logging system '" + name + "' is available but not useable.");
+ }
+ return false;
+ }
+ }
+
+ /**
+ * Attempt to find an attribute (see method setAttribute) or a
+ * system property with the provided name and return its value.
+ * <p>
+ * 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.
+ *
+ * @return the value associated with the property, or null.
+ */
+ private String getConfigurationValue(String property) {
+ if (isDiagnosticsEnabled()) {
+ logDiagnostic("[ENV] Trying to get configuration for item " + property);
+ }
+
+ Object valueObj = getAttribute(property);
+ if (valueObj != null) {
+ if (isDiagnosticsEnabled()) {
+ logDiagnostic("[ENV] Found LogFactory attribute [" + valueObj + "] for " + property);
+ }
+ return valueObj.toString();
+ }
+
+ if (isDiagnosticsEnabled()) {
+ logDiagnostic("[ENV] No LogFactory attribute found for " + property);
}
- // Identify the corresponding constructor to be used
try {
- logConstructor = logClass.getConstructor(logConstructorSignature);
- return (logConstructor);
- } catch (Throwable t) {
- throw new LogConfigurationException
- ("No suitable Log constructor " +
- logConstructorSignature+ " for " + logClassName, t);
+ String value = System.getProperty(property);
+ if (value != null) {
+ if (isDiagnosticsEnabled()) {
+ logDiagnostic("[ENV] Found system property [" + value + "] for " + property);
+ }
+ return value;
}
+
+ if (isDiagnosticsEnabled()) {
+ logDiagnostic("[ENV] No system property found for property " + property);
+ }
+ } catch (SecurityException e) {
+ if (isDiagnosticsEnabled()) {
+ logDiagnostic("[ENV] Security prevented reading system property " + property);
+ }
+ }
+
+ if (isDiagnosticsEnabled()) {
+ logDiagnostic("[ENV] No configuration defined for item " + property);
}
+ return null;
+ }
/**
- * MUST KEEP THIS METHOD PRIVATE.
+ * Get the setting for the user-configurable behaviour specified by key.
+ * If nothing has explicitly been set, then return dflt.
+ */
+ private boolean getBooleanConfiguration(String key, boolean dflt) {
+ String val = getConfigurationValue(key);
+ if (val == null)
+ return dflt;
+ return Boolean.valueOf(val).booleanValue();
+ }
+
+ /**
+ * 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.
+ */
+ private void initConfiguration() {
+ allowFlawedContext = getBooleanConfiguration(ALLOW_FLAWED_CONTEXT_PROPERTY, true);
+ allowFlawedDiscovery = getBooleanConfiguration(ALLOW_FLAWED_DISCOVERY_PROPERTY, true);
+ allowFlawedHierarchy = getBooleanConfiguration(ALLOW_FLAWED_HIERARCHY_PROPERTY, true);
+ }
+
+
+ /**
+ * Attempts to create a Log instance for the given category name.
+ * Follows the discovery process described in the class javadoc.
*
- * <p>Exposing this method outside of
- * <code>org.apache.commons.logging.LogFactoryImpl</code>
- * will create a security violation:
- * This method uses <code>AccessController.doPrivileged()</code>.
- * </p>
+ * @param logCategory the name of the log category
*
- * Load a class, try first the thread class loader, and
- * if it fails use the loader that loaded this class.
+ * @throws LogConfigurationException if an error in discovery occurs,
+ * or if no adapter at all can be instantiated
*/
- private static Class loadClass( final String name )
- throws ClassNotFoundException
+ private Log discoverLogImplementation(String logCategory)
+ throws LogConfigurationException
{
- Object result = AccessController.doPrivileged(
- new PrivilegedAction() {
- public Object run() {
- ClassLoader threadCL = getContextClassLoader();
- if (threadCL != null) {
- try {
- return threadCL.loadClass(name);
- } catch( ClassNotFoundException ex ) {
- // ignore
+ if (isDiagnosticsEnabled()) {
+ logDiagnostic("Discovering a Log implementation...");
}
+
+ initConfiguration();
+
+ Log result = null;
+
+ // See if the user specified the Log implementation to use
+ String specifiedLogClassName = findUserSpecifiedLogClassName();
+
+ if (specifiedLogClassName != null) {
+ if (isDiagnosticsEnabled()) {
+ logDiagnostic("Attempting to load user-specified log class '" +
+ specifiedLogClassName + "'...");
+ }
+
+ result = createLogFromClass(specifiedLogClassName,
+ logCategory,
+ true);
+ if (result == null) {
+ StringBuffer messageBuffer = new StringBuffer("User-specified log class '");
+ messageBuffer.append(specifiedLogClassName);
+ messageBuffer.append("' cannot be found or is not useable.");
+
+ // Mistyping or misspelling names is a common fault.
+ // Construct a good error message, if we can
+ if (specifiedLogClassName != null) {
+ informUponSimilarName(messageBuffer, specifiedLogClassName, LOGGING_IMPL_LOG4J_LOGGER);
+ informUponSimilarName(messageBuffer, specifiedLogClassName, LOGGING_IMPL_JDK14_LOGGER);
+ informUponSimilarName(messageBuffer, specifiedLogClassName, LOGGING_IMPL_LUMBERJACK_LOGGER);
+ informUponSimilarName(messageBuffer, specifiedLogClassName, LOGGING_IMPL_SIMPLE_LOGGER);
+ }
+ throw new LogConfigurationException(messageBuffer.toString());
+ }
+
+ return result;
+ }
+
+ // No user specified log; try to discover what's on the classpath
+ //
+ // Note that we deliberately loop here over classesToDiscover and
+ // expect method createLogFromClass to loop over the possible source
+ // classloaders. The effect is:
+ // for each discoverable log adapter
+ // for each possible classloader
+ // see if it works
+ //
+ // It appears reasonable at first glance to do the opposite:
+ // for each possible classloader
+ // for each discoverable log adapter
+ // see if it works
+ //
+ // The latter certainly has advantages for user-installable logging
+ // libraries such as log4j; in a webapp for example this code should
+ // first check whether the user has provided any of the possible
+ // logging libraries before looking in the parent classloader.
+ // Unfortunately, however, Jdk14Logger will always work in jvm>=1.4,
+ // and SimpleLog will always work in any JVM. So the loop would never
+ // ever look for logging libraries in the parent classpath. Yet many
+ // users would expect that putting log4j there would cause it to be
+ // detected (and this is the historical JCL behaviour). So we go with
+ // the first approach. A user that has bundled a specific logging lib
+ // in a webapp should use a commons-logging.properties file or a
+ // service file in META-INF to force use of that logging lib anyway,
+ // rather than relying on discovery.
+
+ if (isDiagnosticsEnabled()) {
+ logDiagnostic(
+ "No user-specified Log implementation; performing discovery" +
+ " using the standard supported logging implementations...");
}
- try {
- return Class.forName( name );
- } catch (ClassNotFoundException e) {
- return e;
+ for(int i=0; (i<classesToDiscover.length) && (result == null); ++i) {
+ result = createLogFromClass(classesToDiscover[i], logCategory, true);
}
+
+ if (result == null) {
+ throw new LogConfigurationException
+ ("No suitable Log implementation");
+ }
+
+ return result;
}
- });
- if (result instanceof Class)
- return (Class)result;
- throw (ClassNotFoundException)result;
+ /**
+ * Appends message if the given name is similar to the candidate.
+ * @param messageBuffer <code>StringBuffer</code> the message should be appended to,
+ * not null
+ * @param name the (trimmed) name to be test against the candidate, not null
+ * @param candidate the candidate name (not null)
+ */
+ private void informUponSimilarName(final StringBuffer messageBuffer, final String name,
+ final String candidate) {
+ if (name.equals(candidate)) {
+ // Don't suggest a name that is exactly the same as the one the
+ // user tried...
+ return;
+ }
+
+ // If the user provides a name that is in the right package, and gets
+ // the first 5 characters of the adapter class right (ignoring case),
+ // then suggest the candidate adapter class name.
+ if (name.regionMatches(true, 0, candidate, 0, PKG_LEN + 5)) {
+ messageBuffer.append(" Did you mean '");
+ messageBuffer.append(candidate);
+ messageBuffer.append("'?");
+ }
}
/**
- * Is <em>JDK 1.3 with Lumberjack</em> logging available?
+ * Checks system properties and the attribute map for
+ * a Log implementation specified by the user under the
+ * property names {@link #LOG_PROPERTY} or {@link #LOG_PROPERTY_OLD}.
+ *
+ * @return classname specified by the user, or <code>null</code>
*/
- protected boolean isJdk13LumberjackAvailable() {
+ private String findUserSpecifiedLogClassName()
+ {
+ if (isDiagnosticsEnabled()) {
+ logDiagnostic("Trying to get log class from attribute '" + LOG_PROPERTY + "'");
+ }
+ String specifiedClass = (String) getAttribute(LOG_PROPERTY);
+ if (specifiedClass == null) { // @deprecated
+ if (isDiagnosticsEnabled()) {
+ logDiagnostic("Trying to get log class from attribute '" +
+ LOG_PROPERTY_OLD + "'");
+ }
+ specifiedClass = (String) getAttribute(LOG_PROPERTY_OLD);
+ }
+
+ if (specifiedClass == null) {
+ if (isDiagnosticsEnabled()) {
+ logDiagnostic("Trying to get log class from system property '" +
+ LOG_PROPERTY + "'");
+ }
try {
- loadClass("java.util.logging.Logger");
- loadClass("org.apache.commons.logging.impl.Jdk13LumberjackLogger");
- return (true);
- } catch (Throwable t) {
- return (false);
+ specifiedClass = System.getProperty(LOG_PROPERTY);
+ } catch (SecurityException e) {
+ if (isDiagnosticsEnabled()) {
+ logDiagnostic("No access allowed to system property '" +
+ LOG_PROPERTY + "' - " + e.getMessage());
+ }
+ }
}
+ if (specifiedClass == null) { // @deprecated
+ if (isDiagnosticsEnabled()) {
+ logDiagnostic("Trying to get log class from system property '" +
+ LOG_PROPERTY_OLD + "'");
+ }
+ try {
+ specifiedClass = System.getProperty(LOG_PROPERTY_OLD);
+ } catch (SecurityException e) {
+ if (isDiagnosticsEnabled()) {
+ logDiagnostic("No access allowed to system property '" +
+ LOG_PROPERTY_OLD + "' - " + e.getMessage());
+ }
+ }
+ }
+
+ // Remove any whitespace; it's never valid in a classname so its
+ // presence just means a user mistake. As we know what they meant,
+ // we may as well strip the spaces.
+ if (specifiedClass != null) {
+ specifiedClass = specifiedClass.trim();
+ }
+
+ return specifiedClass;
}
/**
- * <p>Return <code>true</code> if <em>JDK 1.4 or later</em> logging
- * is available. Also checks that the <code>Throwable</code> class
- * supports <code>getStackTrace()</code>, which is required by
- * Jdk14Logger.</p>
- */
- protected boolean isJdk14Available() {
+ * Attempts to load the given class, find a suitable constructor,
+ * and instantiate an instance of Log.
+ *
+ * @param logAdapterClassName classname of the Log implementation
+ *
+ * @param logCategory argument to pass to the Log implementation's
+ * constructor
+ *
+ * @param affectState <code>true</code> if this object's state should
+ * be affected by this method call, <code>false</code> otherwise.
+ *
+ * @return 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.
+ */
+ private Log createLogFromClass(String logAdapterClassName,
+ String logCategory,
+ boolean affectState)
+ throws LogConfigurationException {
+ if (isDiagnosticsEnabled()) {
+ logDiagnostic("Attempting to instantiate '" + logAdapterClassName + "'");
+ }
+
+ Object[] params = { logCategory };
+ Log logAdapter = null;
+ Constructor constructor = null;
+
+ Class logAdapterClass = null;
+ ClassLoader currentCL = getBaseClassLoader();
+
+ for(;;) {
+ // Loop through the classloader hierarchy trying to find
+ // a viable classloader.
+ logDiagnostic(
+ "Trying to load '"
+ + logAdapterClassName
+ + "' from classloader "
+ + objectId(currentCL));
try {
- loadClass("java.util.logging.Logger");
- loadClass("org.apache.commons.logging.impl.Jdk14Logger");
- Class throwable = loadClass("java.lang.Throwable");
- if (throwable.getDeclaredMethod("getStackTrace", null) == null) {
- return (false);
+ if (isDiagnosticsEnabled()) {
+ // Show the location of the first occurrence of the .class file
+ // in the classpath. This is the location that ClassLoader.loadClass
+ // will load the class from -- unless the classloader is doing
+ // something weird.
+ URL url;
+ String resourceName = logAdapterClassName.replace('.', '/') + ".class";
+ if (currentCL != null) {
+ url = currentCL.getResource(resourceName );
+ } else {
+ url = ClassLoader.getSystemResource(resourceName + ".class");
}
- return (true);
+
+ if (url == null) {
+ logDiagnostic("Class '" + logAdapterClassName + "' [" + resourceName + "] cannot be found.");
+ } else {
+ logDiagnostic("Class '" + logAdapterClassName + "' was found at '" + url + "'");
+ }
+ }
+
+ Class c = null;
+ try {
+ c = Class.forName(logAdapterClassName, true, currentCL);
+ } catch (ClassNotFoundException originalClassNotFoundException) {
+ // The current classloader was unable to find the log adapter
+ // in this or any ancestor classloader. There's no point in
+ // trying higher up in the hierarchy in this case..
+ String msg = "" + originalClassNotFoundException.getMessage();
+ logDiagnostic(
+ "The log adapter '"
+ + logAdapterClassName
+ + "' is not available via classloader "
+ + objectId(currentCL)
+ + ": "
+ + msg.trim());
+ try {
+ // Try the class classloader.
+ // This may work in cases where the TCCL
+ // does not contain the code executed or JCL.
+ // This behaviour indicates that the application
+ // classloading strategy is not consistent with the
+ // Java 1.2 classloading guidelines but JCL can
+ // and so should handle this case.
+ c = Class.forName(logAdapterClassName);
+ } catch (ClassNotFoundException secondaryClassNotFoundException) {
+ // no point continuing: this adapter isn't available
+ msg = "" + secondaryClassNotFoundException.getMessage();
+ logDiagnostic(
+ "The log adapter '"
+ + logAdapterClassName
+ + "' is not available via the LogFactoryImpl class classloader: "
+ + msg.trim());
+ break;
+ }
+ }
+
+ constructor = c.getConstructor(logConstructorSignature);
+ Object o = constructor.newInstance(params);
+
+ // Note that we do this test after trying to create an instance
+ // [rather than testing Log.class.isAssignableFrom(c)] so that
+ // we don't complain about Log hierarchy problems when the
+ // adapter couldn't be instantiated anyway.
+ if (o instanceof Log) {
+ logAdapterClass = c;
+ logAdapter = (Log) o;
+ break;
+ }
+
+ // Oops, we have a potential problem here. An adapter class
+ // has been found and its underlying lib is present too, but
+ // there are multiple Log interface classes available making it
+ // impossible to cast to the type the caller wanted. We
+ // certainly can't use this logger, but we need to know whether
+ // to keep on discovering or terminate now.
+ //
+ // The handleFlawedHierarchy method will throw
+ // LogConfigurationException if it regards this problem as
+ // fatal, and just return if not.
+ handleFlawedHierarchy(currentCL, c);
+ } catch (NoClassDefFoundError e) {
+ // We were able to load the adapter but it had references to
+ // other classes that could not be found. This simply means that
+ // the underlying logger library is not present in this or any
+ // ancestor classloader. There's no point in trying higher up
+ // in the hierarchy in this case..
+ String msg = "" + e.getMessage();
+ logDiagnostic(
+ "The log adapter '"
+ + logAdapterClassName
+ + "' is missing dependencies when loaded via classloader "
+ + objectId(currentCL)
+ + ": "
+ + msg.trim());
+ break;
+ } catch (ExceptionInInitializerError e) {
+ // A static initializer block or the initializer code associated
+ // with a static variable on the log adapter class has thrown
+ // an exception.
+ //
+ // We treat this as meaning the adapter's underlying logging
+ // library could not be found.
+ String msg = "" + e.getMessage();
+ logDiagnostic(
+ "The log adapter '"
+ + logAdapterClassName
+ + "' is unable to initialize itself when loaded via classloader "
+ + objectId(currentCL)
+ + ": "
+ + msg.trim());
+ break;
+ } catch(LogConfigurationException e) {
+ // call to handleFlawedHierarchy above must have thrown
+ // a LogConfigurationException, so just throw it on
+ throw e;
+ } catch(Throwable t) {
+ // handleFlawedDiscovery will determine whether this is a fatal
+ // problem or not. If it is fatal, then a LogConfigurationException
+ // will be thrown.
+ handleFlawedDiscovery(logAdapterClassName, currentCL, t);
+ }
+
+ if (currentCL == null) {
+ break;
+ }
+
+ // try the parent classloader
+ currentCL = currentCL.getParent();
+ }
+
+ if ((logAdapter != null) && affectState) {
+ // We've succeeded, so set instance fields
+ this.logClassName = logAdapterClassName;
+ this.logConstructor = constructor;
+
+ // Identify the <code>setLogFactory</code> method (if there is one)
+ try {
+ this.logMethod = logAdapterClass.getMethod("setLogFactory",
+ logMethodSignature);
+ logDiagnostic("Found method setLogFactory(LogFactory) in '"
+ + logAdapterClassName + "'");
} catch (Throwable t) {
- return (false);
+ this.logMethod = null;
+ logDiagnostic(
+ "[INFO] '" + logAdapterClassName
+ + "' from classloader " + objectId(currentCL)
+ + " does not declare optional method "
+ + "setLogFactory(LogFactory)");
+ }
+
+ logDiagnostic(
+ "Log adapter '" + logAdapterClassName
+ + "' from classloader " + objectId(logAdapterClass.getClassLoader())
+ + " has been selected for use.");
+ }
+
+ return logAdapter;
}
+
+
+ /**
+ * Return the classloader from which we should try to load the logging
+ * adapter classes.
+ * <p>
+ * 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 <i>and</i> the allowFlawedContext option
+ * has been set then the classloader which loaded this class is returned
+ * instead.
+ * <p>
+ * 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.
+ *
+ */
+ private ClassLoader getBaseClassLoader() throws LogConfigurationException {
+ ClassLoader thisClassLoader = getClassLoader(LogFactoryImpl.class);
+
+ if (useTCCL == false) {
+ return thisClassLoader;
}
+ ClassLoader contextClassLoader = getContextClassLoader();
+
+ ClassLoader baseClassLoader = getLowestClassLoader(
+ contextClassLoader, thisClassLoader);
+
+ if (baseClassLoader == null) {
+ // The two classloaders are not part of a parent child relationship.
+ // In some classloading setups (e.g. JBoss with its
+ // UnifiedLoaderRepository) this can still work, so if user hasn't
+ // forbidden it, just return the contextClassLoader.
+ if (allowFlawedContext) {
+ if (isDiagnosticsEnabled()) {
+ logDiagnostic(
+ "[WARNING] the context classloader is not part of a"
+ + " parent-child relationship with the classloader that"
+ + " loaded LogFactoryImpl.");
+ }
+ // If contextClassLoader were null, getLowestClassLoader() would
+ // have returned thisClassLoader. The fact we are here means
+ // contextClassLoader is not null, so we can just return it.
+ return contextClassLoader;
+ }
+ else {
+ throw new LogConfigurationException(
+ "Bad classloader hierarchy; LogFactoryImpl was loaded via"
+ + " a classloader that is not related to the current context"
+ + " classloader.");
+ }
+ }
+
+ if (baseClassLoader != contextClassLoader) {
+ // We really should just use the contextClassLoader as the starting
+ // point for scanning for log adapter classes. However it is expected
+ // that there are a number of broken systems out there which create
+ // custom classloaders but fail to set the context classloader so
+ // we handle those flawed systems anyway.
+ if (allowFlawedContext) {
+ if (isDiagnosticsEnabled()) {
+ logDiagnostic(
+ "Warning: the context classloader is an ancestor of the"
+ + " classloader that loaded LogFactoryImpl; it should be"
+ + " the same or a descendant. The application using"
+ + " commons-logging should ensure the context classloader"
+ + " is used correctly.");
+ }
+ } else {
+ throw new LogConfigurationException(
+ "Bad classloader hierarchy; LogFactoryImpl was loaded via"
+ + " a classloader that is not related to the current context"
+ + " classloader.");
+ }
+ }
+
+ return baseClassLoader;
+ }
/**
- * Is a <em>Log4J</em> implementation available?
+ * Given two related classloaders, return the one which is a child of
+ * the other.
+ * <p>
+ * @param c1 is a classloader (including the null classloader)
+ * @param c2 is a classloader (including the null classloader)
+ *
+ * @return 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.
*/
- protected boolean isLog4JAvailable() {
+ private ClassLoader getLowestClassLoader(ClassLoader c1, ClassLoader c2) {
+ // TODO: use AccessController when dealing with classloaders here
- try {
- loadClass("org.apache.log4j.Logger");
- loadClass("org.apache.commons.logging.impl.Log4JLogger");
- return (true);
- } catch (Throwable t) {
- return (false);
+ if (c1 == null)
+ return c2;
+
+ if (c2 == null)
+ return c1;
+
+ ClassLoader current;
+
+ // scan c1's ancestors to find c2
+ current = c1;
+ while (current != null) {
+ if (current == c2)
+ return c1;
+ current = current.getParent();
}
+
+ // scan c2's ancestors to find c1
+ current = c2;
+ while (current != null) {
+ if (current == c1)
+ return c2;
+ current = current.getParent();
}
+ return null;
+ }
/**
- * Create and return a new {@link org.apache.commons.logging.Log}
- * instance for the specified name.
+ * Generates an internal diagnostic logging of the discovery failure and
+ * then throws a <code>LogConfigurationException</code> that wraps
+ * the passed <code>Throwable</code>.
*
- * @param name Name of the new logger
+ * @param logAdapterClassName is the class name of the Log implementation
+ * that could not be instantiated. Cannot be <code>null</code>.
*
- * @exception LogConfigurationException if a new instance cannot
- * be created
+ * @param classLoader is the classloader that we were trying to load the
+ * logAdapterClassName from when the exception occurred.
+ *
+ * @param discoveryFlaw is the Throwable created by the classloader
+ *
+ * @throws LogConfigurationException ALWAYS
*/
- protected Log newInstance(String name) throws LogConfigurationException {
+ private void handleFlawedDiscovery(String logAdapterClassName,
+ ClassLoader classLoader,
+ Throwable discoveryFlaw) {
- Log instance = null;
- try {
- Object params[] = new Object[1];
- params[0] = name;
- instance = (Log) getLogConstructor().newInstance(params);
- if (logMethod != null) {
- params[0] = this;
- logMethod.invoke(instance, params);
+ if (isDiagnosticsEnabled()) {
+ logDiagnostic("Could not instantiate Log '"
+ + logAdapterClassName + "' -- "
+ + discoveryFlaw.getClass().getName() + ": "
+ + discoveryFlaw.getLocalizedMessage());
}
- return (instance);
- } catch (InvocationTargetException e) {
- Throwable c = e.getTargetException();
- if (c != null) {
- throw new LogConfigurationException(c);
- } else {
- throw new LogConfigurationException(e);
+
+ if (!allowFlawedDiscovery) {
+ throw new LogConfigurationException(discoveryFlaw);
}
- } catch (Throwable t) {
- throw new LogConfigurationException(t);
}
+
+ /**
+ * Report a problem loading the log adapter, then either return
+ * (if the situation is considered recoverable) or throw a
+ * LogConfigurationException.
+ * <p>
+ * There are two possible reasons why we successfully loaded the
+ * specified log adapter class then failed to cast it to a Log object:
+ * <ol>
+ * <li>the specific class just doesn't implement the Log interface
+ * (user screwed up), or
+ * <li> the specified class has bound to a Log class loaded by some other
+ * classloader; Log at classloaderX cannot be cast to Log at classloaderY.
+ * </ol>
+ * <p>
+ * Here we try to figure out which case has occurred so we can give the
+ * user some reasonable feedback.
+ *
+ * @param badClassLoader is the classloader we loaded the problem class from,
+ * ie it is equivalent to badClass.getClassLoader().
+ *
+ * @param 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.
+ */
+ private void handleFlawedHierarchy(ClassLoader badClassLoader, Class badClass)
+ throws LogConfigurationException {
+
+ boolean implementsLog = false;
+ String logInterfaceName = Log.class.getName();
+ Class interfaces[] = badClass.getInterfaces();
+ for (int i = 0; i < interfaces.length; i++) {
+ if (logInterfaceName.equals(interfaces[i].getName())) {
+ implementsLog = true;
+ break;
+ }
}
+ if (implementsLog) {
+ // the class does implement an interface called Log, but
+ // it is in the wrong classloader
+ if (isDiagnosticsEnabled()) {
+ try {
+ ClassLoader logInterfaceClassLoader = getClassLoader(Log.class);
+ logDiagnostic(
+ "Class '" + badClass.getName()
+ + "' was found in classloader "
+ + objectId(badClassLoader)
+ + ". It is bound to a Log interface which is not"
+ + " the one loaded from classloader "
+ + objectId(logInterfaceClassLoader));
+ } catch (Throwable t) {
+ logDiagnostic(
+ "Error while trying to output diagnostics about"
+ + " bad class '" + badClass + "'");
+ }
+ }
+ if (!allowFlawedHierarchy) {
+ StringBuffer msg = new StringBuffer();
+ msg.append("Terminating logging for this context ");
+ msg.append("due to bad log hierarchy. ");
+ msg.append("You have more than one version of '");
+ msg.append(Log.class.getName());
+ msg.append("' visible.");
+ if (isDiagnosticsEnabled()) {
+ logDiagnostic(msg.toString());
+ }
+ throw new LogConfigurationException(msg.toString());
+ }
+
+ if (isDiagnosticsEnabled()) {
+ StringBuffer msg = new StringBuffer();
+ msg.append("Warning: bad log hierarchy. ");
+ msg.append("You have more than one version of '");
+ msg.append(Log.class.getName());
+ msg.append("' visible.");
+ logDiagnostic(msg.toString());
+ }
+ } else {
+ // this is just a bad adapter class
+ if (!allowFlawedDiscovery) {
+ StringBuffer msg = new StringBuffer();
+ msg.append("Terminating logging for this context. ");
+ msg.append("Log class '");
+ msg.append(badClass.getName());
+ msg.append("' does not implement the Log interface.");
+ if (isDiagnosticsEnabled()) {
+ logDiagnostic(msg.toString());
+ }
+
+ throw new LogConfigurationException(msg.toString());
+ }
+
+ if (isDiagnosticsEnabled()) {
+ StringBuffer msg = new StringBuffer();
+ msg.append("[WARNING] Log class '");
+ msg.append(badClass.getName());
+ msg.append("' does not implement the Log interface.");
+ logDiagnostic(msg.toString());
+ }
+ }
+ }
}
1.2 +291 -223 apache/commons-logging/src/java/org/apache/commons/logging/impl/AvalonLogger.java
(In the diff below, changes in quantity of whitespace are not shown.)
Index: AvalonLogger.java
===================================================================
RCS file: /cvsroot/jboss/apache/commons-logging/src/java/org/apache/commons/logging/impl/AvalonLogger.java,v
retrieving revision 1.1
retrieving revision 1.2
diff -u -b -r1.1 -r1.2
--- AvalonLogger.java 17 Apr 2006 21:00:04 -0000 1.1
+++ AvalonLogger.java 9 Feb 2007 06:57:15 -0000 1.2
@@ -1,5 +1,5 @@
/*
- * Copyright 2001-2004 The Apache Software Foundation.
+ * Copyright 2001-2004,2006 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,7 +16,6 @@
package org.apache.commons.logging.impl;
-import java.io.Serializable;
import org.apache.avalon.framework.logger.Logger;
import org.apache.commons.logging.Log;
@@ -39,18 +38,25 @@
* to child loggers of this <code>Logger</code>.
* </li>
* </ul>
- *
+ * <p>
+ * <strong>Note:</strong> <code>AvalonLogger</code> does not implement Serializable
+ * because the constructors available for it make this impossible to achieve in all
+ * circumstances; there is no way to "reconnect" to an underlying Logger object on
+ * deserialization if one was just passed in to the constructor of the original
+ * object. This class <i>was</i> marked Serializable in the 1.0.4 release of
+ * commons-logging, but this never actually worked (a NullPointerException would
+ * be thrown as soon as the deserialized object was used), so removing this marker
+ * is not considered to be an incompatible change.
+ * </p>
* @author <a href="mailto:neeme at apache.org">Neeme Praks</a>
- * @version $Revision: 1.1 $ $Date: 2006/04/17 21:00:04 $
+ * @version $Revision: 1.2 $ $Date: 2007/02/09 06:57:15 $
*/
-public class AvalonLogger implements Log, Serializable {
+public class AvalonLogger implements Log {
/** Ancesteral avalon logger */
private static Logger defaultLogger = null;
/** Avalon logger used to perform log */
private transient Logger logger = null;
- /** The name of this logger */
- private String name = null;
/**
* Constructs an <code>AvalonLogger</code> that outputs to the given
@@ -58,7 +64,6 @@
* @param logger the avalon logger implementation to delegate to
*/
public AvalonLogger(Logger logger) {
- this.name = name;
this.logger = logger;
}
@@ -70,7 +75,7 @@
public AvalonLogger(String name) {
if (defaultLogger == null)
throw new NullPointerException("default logger has to be specified if this constructor is used!");
- this.logger = getLogger();
+ this.logger = defaultLogger.getChildLogger(name);
}
/**
@@ -78,9 +83,6 @@
* @return avalon logger implementation
*/
public Logger getLogger() {
- if (logger == null) {
- logger = defaultLogger.getChildLogger(name);
- }
return logger;
}
@@ -95,62 +97,100 @@
}
/**
- * @see org.apache.commons.logging.Log#debug(java.lang.Object, java.lang.Throwable)
+ * Logs a message with
+ * <code>org.apache.avalon.framework.logger.Logger.debug</code>.
+ *
+ * @param message to log
+ * @param t log this cause
+ * @see org.apache.commons.logging.Log#debug(Object, Throwable)
*/
- public void debug(Object o, Throwable t) {
- if (getLogger().isDebugEnabled()) getLogger().debug(String.valueOf(o), t);
+ public void debug(Object message, Throwable t) {
+ if (getLogger().isDebugEnabled()) getLogger().debug(String.valueOf(message), t);
}
/**
- * @see org.apache.commons.logging.Log#debug(java.lang.Object)
+ * Logs a message with
+ * <code>org.apache.avalon.framework.logger.Logger.debug</code>.
+ *
+ * @param message to log.
+ * @see org.apache.commons.logging.Log#debug(Object)
*/
- public void debug(Object o) {
- if (getLogger().isDebugEnabled()) getLogger().debug(String.valueOf(o));
+ public void debug(Object message) {
+ if (getLogger().isDebugEnabled()) getLogger().debug(String.valueOf(message));
}
/**
- * @see org.apache.commons.logging.Log#error(java.lang.Object, java.lang.Throwable)
+ * Logs a message with
+ * <code>org.apache.avalon.framework.logger.Logger.error</code>.
+ *
+ * @param message to log
+ * @param t log this cause
+ * @see org.apache.commons.logging.Log#error(Object, Throwable)
*/
- public void error(Object o, Throwable t) {
- if (getLogger().isErrorEnabled()) getLogger().error(String.valueOf(o), t);
+ public void error(Object message, Throwable t) {
+ if (getLogger().isErrorEnabled()) getLogger().error(String.valueOf(message), t);
}
/**
- * @see org.apache.commons.logging.Log#error(java.lang.Object)
+ * Logs a message with
+ * <code>org.apache.avalon.framework.logger.Logger.error</code>.
+ *
+ * @param message to log
+ * @see org.apache.commons.logging.Log#error(Object)
*/
- public void error(Object o) {
- if (getLogger().isErrorEnabled()) getLogger().error(String.valueOf(o));
+ public void error(Object message) {
+ if (getLogger().isErrorEnabled()) getLogger().error(String.valueOf(message));
}
/**
- * @see org.apache.commons.logging.Log#fatal(java.lang.Object, java.lang.Throwable)
+ * Logs a message with
+ * <code>org.apache.avalon.framework.logger.Logger.fatalError</code>.
+ *
+ * @param message to log.
+ * @param t log this cause.
+ * @see org.apache.commons.logging.Log#fatal(Object, Throwable)
*/
- public void fatal(Object o, Throwable t) {
- if (getLogger().isFatalErrorEnabled()) getLogger().fatalError(String.valueOf(o), t);
+ public void fatal(Object message, Throwable t) {
+ if (getLogger().isFatalErrorEnabled()) getLogger().fatalError(String.valueOf(message), t);
}
/**
- * @see org.apache.commons.logging.Log#fatal(java.lang.Object)
+ * Logs a message with
+ * <code>org.apache.avalon.framework.logger.Logger.fatalError</code>.
+ *
+ * @param message to log
+ * @see org.apache.commons.logging.Log#fatal(Object)
*/
- public void fatal(Object o) {
- if (getLogger().isFatalErrorEnabled()) getLogger().fatalError(String.valueOf(o));
+ public void fatal(Object message) {
+ if (getLogger().isFatalErrorEnabled()) getLogger().fatalError(String.valueOf(message));
}
/**
- * @see org.apache.commons.logging.Log#info(java.lang.Object, java.lang.Throwable)
+ * Logs a message with
+ * <code>org.apache.avalon.framework.logger.Logger.info</code>.
+ *
+ * @param message to log
+ * @param t log this cause
+ * @see org.apache.commons.logging.Log#info(Object, Throwable)
*/
- public void info(Object o, Throwable t) {
- if (getLogger().isInfoEnabled()) getLogger().info(String.valueOf(o), t);
+ public void info(Object message, Throwable t) {
+ if (getLogger().isInfoEnabled()) getLogger().info(String.valueOf(message), t);
}
/**
- * @see org.apache.commons.logging.Log#info(java.lang.Object)
+ * Logs a message with
+ * <code>org.apache.avalon.framework.logger.Logger.info</code>.
+ *
+ * @param message to log
+ * @see org.apache.commons.logging.Log#info(Object)
*/
- public void info(Object o) {
- if (getLogger().isInfoEnabled()) getLogger().info(String.valueOf(o));
+ public void info(Object message) {
+ if (getLogger().isInfoEnabled()) getLogger().info(String.valueOf(message));
}
/**
+ * Is logging to
+ * <code>org.apache.avalon.framework.logger.Logger.debug</code> enabled?
* @see org.apache.commons.logging.Log#isDebugEnabled()
*/
public boolean isDebugEnabled() {
@@ -158,6 +198,8 @@
}
/**
+ * Is logging to
+ * <code>org.apache.avalon.framework.logger.Logger.error</code> enabled?
* @see org.apache.commons.logging.Log#isErrorEnabled()
*/
public boolean isErrorEnabled() {
@@ -165,6 +207,8 @@
}
/**
+ * Is logging to
+ * <code>org.apache.avalon.framework.logger.Logger.fatalError</code> enabled?
* @see org.apache.commons.logging.Log#isFatalEnabled()
*/
public boolean isFatalEnabled() {
@@ -172,6 +216,8 @@
}
/**
+ * Is logging to
+ * <code>org.apache.avalon.framework.logger.Logger.info</code> enabled?
* @see org.apache.commons.logging.Log#isInfoEnabled()
*/
public boolean isInfoEnabled() {
@@ -179,6 +225,8 @@
}
/**
+ * Is logging to
+ * <code>org.apache.avalon.framework.logger.Logger.debug</code> enabled?
* @see org.apache.commons.logging.Log#isTraceEnabled()
*/
public boolean isTraceEnabled() {
@@ -186,6 +234,8 @@
}
/**
+ * Is logging to
+ * <code>org.apache.avalon.framework.logger.Logger.warn</code> enabled?
* @see org.apache.commons.logging.Log#isWarnEnabled()
*/
public boolean isWarnEnabled() {
@@ -193,31 +243,49 @@
}
/**
- * @see org.apache.commons.logging.Log#trace(java.lang.Object, java.lang.Throwable)
+ * Logs a message with
+ * <code>org.apache.avalon.framework.logger.Logger.debug</code>.
+ *
+ * @param message to log.
+ * @param t log this cause.
+ * @see org.apache.commons.logging.Log#trace(Object, Throwable)
*/
- public void trace(Object o, Throwable t) {
- if (getLogger().isDebugEnabled()) getLogger().debug(String.valueOf(o), t);
+ public void trace(Object message, Throwable t) {
+ if (getLogger().isDebugEnabled()) getLogger().debug(String.valueOf(message), t);
}
/**
- * @see org.apache.commons.logging.Log#trace(java.lang.Object)
+ * Logs a message with
+ * <code>org.apache.avalon.framework.logger.Logger.debug</code>.
+ *
+ * @param message to log
+ * @see org.apache.commons.logging.Log#trace(Object)
*/
- public void trace(Object o) {
- if (getLogger().isDebugEnabled()) getLogger().debug(String.valueOf(o));
+ public void trace(Object message) {
+ if (getLogger().isDebugEnabled()) getLogger().debug(String.valueOf(message));
}
/**
- * @see org.apache.commons.logging.Log#warn(java.lang.Object, java.lang.Throwable)
+ * Logs a message with
+ * <code>org.apache.avalon.framework.logger.Logger.warn</code>.
+ *
+ * @param message to log
+ * @param t log this cause
+ * @see org.apache.commons.logging.Log#warn(Object, Throwable)
*/
- public void warn(Object o, Throwable t) {
- if (getLogger().isWarnEnabled()) getLogger().warn(String.valueOf(o), t);
+ public void warn(Object message, Throwable t) {
+ if (getLogger().isWarnEnabled()) getLogger().warn(String.valueOf(message), t);
}
/**
- * @see org.apache.commons.logging.Log#warn(java.lang.Object)
+ * Logs a message with
+ * <code>org.apache.avalon.framework.logger.Logger.warn</code>.
+ *
+ * @param message to log
+ * @see org.apache.commons.logging.Log#warn(Object)
*/
- public void warn(Object o) {
- if (getLogger().isWarnEnabled()) getLogger().warn(String.valueOf(o));
+ public void warn(Object message) {
+ if (getLogger().isWarnEnabled()) getLogger().warn(String.valueOf(message));
}
}
1.2 +708 -652 apache/commons-logging/src/java/org/apache/commons/logging/impl/SimpleLog.java
(In the diff below, changes in quantity of whitespace are not shown.)
Index: SimpleLog.java
===================================================================
RCS file: /cvsroot/jboss/apache/commons-logging/src/java/org/apache/commons/logging/impl/SimpleLog.java,v
retrieving revision 1.1
retrieving revision 1.2
diff -u -b -r1.1 -r1.2
--- SimpleLog.java 17 Apr 2006 21:00:05 -0000 1.1
+++ SimpleLog.java 9 Feb 2007 06:57:15 -0000 1.2
@@ -70,7 +70,7 @@
* @author Rod Waldhoff
* @author Robert Burrell Donkin
*
- * @version $Id: SimpleLog.java,v 1.1 2006/04/17 21:00:05 starksm Exp $
+ * @version $Id: SimpleLog.java,v 1.2 2007/02/09 06:57:15 starksm Exp $
*/
public class SimpleLog implements Log, Serializable {
@@ -360,7 +360,11 @@
/**
- * <p> Log a message with debug log level.</p>
+ * Logs a message with
+ * <code>org.apache.commons.logging.impl.SimpleLog.LOG_LEVEL_DEBUG</code>.
+ *
+ * @param message to log
+ * @see org.apache.commons.logging.Log#debug(Object)
*/
public final void debug(Object message) {
@@ -371,7 +375,12 @@
/**
- * <p> Log an error with debug log level.</p>
+ * Logs a message with
+ * <code>org.apache.commons.logging.impl.SimpleLog.LOG_LEVEL_DEBUG</code>.
+ *
+ * @param message to log
+ * @param t log this cause
+ * @see org.apache.commons.logging.Log#debug(Object, Throwable)
*/
public final void debug(Object message, Throwable t) {
@@ -382,7 +391,11 @@
/**
- * <p> Log a message with trace log level.</p>
+ * Logs a message with
+ * <code>org.apache.commons.logging.impl.SimpleLog.LOG_LEVEL_TRACE</code>.
+ *
+ * @param message to log
+ * @see org.apache.commons.logging.Log#trace(Object)
*/
public final void trace(Object message) {
@@ -393,7 +406,12 @@
/**
- * <p> Log an error with trace log level.</p>
+ * Logs a message with
+ * <code>org.apache.commons.logging.impl.SimpleLog.LOG_LEVEL_TRACE</code>.
+ *
+ * @param message to log
+ * @param t log this cause
+ * @see org.apache.commons.logging.Log#trace(Object, Throwable)
*/
public final void trace(Object message, Throwable t) {
@@ -404,7 +422,11 @@
/**
- * <p> Log a message with info log level.</p>
+ * Logs a message with
+ * <code>org.apache.commons.logging.impl.SimpleLog.LOG_LEVEL_INFO</code>.
+ *
+ * @param message to log
+ * @see org.apache.commons.logging.Log#info(Object)
*/
public final void info(Object message) {
@@ -415,7 +437,12 @@
/**
- * <p> Log an error with info log level.</p>
+ * Logs a message with
+ * <code>org.apache.commons.logging.impl.SimpleLog.LOG_LEVEL_INFO</code>.
+ *
+ * @param message to log
+ * @param t log this cause
+ * @see org.apache.commons.logging.Log#info(Object, Throwable)
*/
public final void info(Object message, Throwable t) {
@@ -426,7 +453,11 @@
/**
- * <p> Log a message with warn log level.</p>
+ * Logs a message with
+ * <code>org.apache.commons.logging.impl.SimpleLog.LOG_LEVEL_WARN</code>.
+ *
+ * @param message to log
+ * @see org.apache.commons.logging.Log#warn(Object)
*/
public final void warn(Object message) {
@@ -437,7 +468,12 @@
/**
- * <p> Log an error with warn log level.</p>
+ * Logs a message with
+ * <code>org.apache.commons.logging.impl.SimpleLog.LOG_LEVEL_WARN</code>.
+ *
+ * @param message to log
+ * @param t log this cause
+ * @see org.apache.commons.logging.Log#warn(Object, Throwable)
*/
public final void warn(Object message, Throwable t) {
@@ -448,7 +484,11 @@
/**
- * <p> Log a message with error log level.</p>
+ * Logs a message with
+ * <code>org.apache.commons.logging.impl.SimpleLog.LOG_LEVEL_ERROR</code>.
+ *
+ * @param message to log
+ * @see org.apache.commons.logging.Log#error(Object)
*/
public final void error(Object message) {
@@ -459,7 +499,12 @@
/**
- * <p> Log an error with error log level.</p>
+ * Logs a message with
+ * <code>org.apache.commons.logging.impl.SimpleLog.LOG_LEVEL_ERROR</code>.
+ *
+ * @param message to log
+ * @param t log this cause
+ * @see org.apache.commons.logging.Log#error(Object, Throwable)
*/
public final void error(Object message, Throwable t) {
@@ -470,7 +515,11 @@
/**
- * <p> Log a message with fatal log level.</p>
+ * Log a message with
+ * <code>org.apache.commons.logging.impl.SimpleLog.LOG_LEVEL_FATAL</code>.
+ *
+ * @param message to log
+ * @see org.apache.commons.logging.Log#fatal(Object)
*/
public final void fatal(Object message) {
@@ -481,7 +530,12 @@
/**
- * <p> Log an error with fatal log level.</p>
+ * Logs a message with
+ * <code>org.apache.commons.logging.impl.SimpleLog.LOG_LEVEL_FATAL</code>.
+ *
+ * @param message to log
+ * @param t log this cause
+ * @see org.apache.commons.logging.Log#fatal(Object, Throwable)
*/
public final void fatal(Object message, Throwable t) {
@@ -586,11 +640,13 @@
if (classLoader == null) {
try {
// Are we running on a JDK 1.2 or later system?
- Method method = Thread.class.getMethod("getContextClassLoader", null);
+ Method method = Thread.class.getMethod("getContextClassLoader",
+ (Class[]) null);
// Get the thread context class loader (if there is one)
try {
- classLoader = (ClassLoader)method.invoke(Thread.currentThread(), null);
+ classLoader = (ClassLoader)method.invoke(Thread.currentThread(),
+ (Class[]) null);
} catch (IllegalAccessException e) {
; // ignore
} catch (InvocationTargetException e) {
1.2 +78 -27 apache/commons-logging/src/java/org/apache/commons/logging/impl/Jdk13LumberjackLogger.java
(In the diff below, changes in quantity of whitespace are not shown.)
Index: Jdk13LumberjackLogger.java
===================================================================
RCS file: /cvsroot/jboss/apache/commons-logging/src/java/org/apache/commons/logging/impl/Jdk13LumberjackLogger.java,v
retrieving revision 1.1
retrieving revision 1.2
diff -u -b -r1.1 -r1.2
--- Jdk13LumberjackLogger.java 17 Apr 2006 21:00:05 -0000 1.1
+++ Jdk13LumberjackLogger.java 9 Feb 2007 06:57:15 -0000 1.2
@@ -38,7 +38,8 @@
* @author <a href="mailto:bloritsch at apache.org">Berin Loritsch</a>
* @author <a href="mailto:donaldp at apache.org">Peter Donald</a>
* @author <a href="mailto:vince256 at comcast.net">Vince Eagen</a>
- * @version $Revision: 1.1 $ $Date: 2006/04/17 21:00:05 $
+ * @version $Revision: 1.2 $ $Date: 2007/02/09 06:57:15 $
+ * @since 1.1
*/
public class Jdk13LumberjackLogger implements Log, Serializable {
@@ -57,6 +58,14 @@
private boolean classAndMethodFound = false;
+ /**
+ * This member variable simply ensures that any attempt to initialise
+ * this class in a pre-1.4 JVM will result in an ExceptionInInitializerError.
+ * It must not be private, as an optimising compiler could detect that it
+ * is not used and optimise it away.
+ */
+ protected static final Level dummyLevel = Level.FINE;
+
// ----------------------------------------------------------- Constructors
@@ -126,7 +135,10 @@
}
/**
- * Log a message with debug log level.
+ * Logs a message with <code>java.util.logging.Level.FINE</code>.
+ *
+ * @param message to log
+ * @see org.apache.commons.logging.Log#debug(Object)
*/
public void debug(Object message) {
log(Level.FINE, String.valueOf(message), null);
@@ -134,7 +146,11 @@
/**
- * Log a message and exception with debug log level.
+ * Logs a message with <code>java.util.logging.Level.FINE</code>.
+ *
+ * @param message to log
+ * @param exception log this cause
+ * @see org.apache.commons.logging.Log#debug(Object, Throwable)
*/
public void debug(Object message, Throwable exception) {
log(Level.FINE, String.valueOf(message), exception);
@@ -142,7 +158,10 @@
/**
- * Log a message with error log level.
+ * Logs a message with <code>java.util.logging.Level.SEVERE</code>.
+ *
+ * @param message to log
+ * @see org.apache.commons.logging.Log#error(Object)
*/
public void error(Object message) {
log(Level.SEVERE, String.valueOf(message), null);
@@ -150,7 +169,11 @@
/**
- * Log a message and exception with error log level.
+ * Logs a message with <code>java.util.logging.Level.SEVERE</code>.
+ *
+ * @param message to log
+ * @param exception log this cause
+ * @see org.apache.commons.logging.Log#error(Object, Throwable)
*/
public void error(Object message, Throwable exception) {
log(Level.SEVERE, String.valueOf(message), exception);
@@ -158,7 +181,10 @@
/**
- * Log a message with fatal log level.
+ * Logs a message with <code>java.util.logging.Level.SEVERE</code>.
+ *
+ * @param message to log
+ * @see org.apache.commons.logging.Log#fatal(Object)
*/
public void fatal(Object message) {
log(Level.SEVERE, String.valueOf(message), null);
@@ -166,7 +192,11 @@
/**
- * Log a message and exception with fatal log level.
+ * Logs a message with <code>java.util.logging.Level.SEVERE</code>.
+ *
+ * @param message to log
+ * @param exception log this cause
+ * @see org.apache.commons.logging.Log#fatal(Object, Throwable)
*/
public void fatal(Object message, Throwable exception) {
log(Level.SEVERE, String.valueOf(message), exception);
@@ -185,7 +215,10 @@
/**
- * Log a message with info log level.
+ * Logs a message with <code>java.util.logging.Level.INFO</code>.
+ *
+ * @param message to log
+ * @see org.apache.commons.logging.Log#info(Object)
*/
public void info(Object message) {
log(Level.INFO, String.valueOf(message), null);
@@ -193,7 +226,11 @@
/**
- * Log a message and exception with info log level.
+ * Logs a message with <code>java.util.logging.Level.INFO</code>.
+ *
+ * @param message to log
+ * @param exception log this cause
+ * @see org.apache.commons.logging.Log#info(Object, Throwable)
*/
public void info(Object message, Throwable exception) {
log(Level.INFO, String.valueOf(message), exception);
@@ -249,7 +286,10 @@
/**
- * Log a message with trace log level.
+ * Logs a message with <code>java.util.logging.Level.FINEST</code>.
+ *
+ * @param message to log
+ * @see org.apache.commons.logging.Log#trace(Object)
*/
public void trace(Object message) {
log(Level.FINEST, String.valueOf(message), null);
@@ -257,7 +297,11 @@
/**
- * Log a message and exception with trace log level.
+ * Logs a message with <code>java.util.logging.Level.FINEST</code>.
+ *
+ * @param message to log
+ * @param exception log this cause
+ * @see org.apache.commons.logging.Log#trace(Object, Throwable)
*/
public void trace(Object message, Throwable exception) {
log(Level.FINEST, String.valueOf(message), exception);
@@ -265,7 +309,10 @@
/**
- * Log a message with warn log level.
+ * Logs a message with <code>java.util.logging.Level.WARNING</code>.
+ *
+ * @param message to log
+ * @see org.apache.commons.logging.Log#warn(Object)
*/
public void warn(Object message) {
log(Level.WARNING, String.valueOf(message), null);
@@ -273,7 +320,11 @@
/**
- * Log a message and exception with warn log level.
+ * Logs a message with <code>java.util.logging.Level.WARNING</code>.
+ *
+ * @param message to log
+ * @param exception log this cause
+ * @see org.apache.commons.logging.Log#warn(Object, Throwable)
*/
public void warn(Object message, Throwable exception) {
log(Level.WARNING, String.valueOf(message), exception);
1.3 +312 -108 apache/commons-logging/src/java/org/apache/commons/logging/impl/Log4JLogger.java
(In the diff below, changes in quantity of whitespace are not shown.)
Index: Log4JLogger.java
===================================================================
RCS file: /cvsroot/jboss/apache/commons-logging/src/java/org/apache/commons/logging/impl/Log4JLogger.java,v
retrieving revision 1.2
retrieving revision 1.3
diff -u -b -r1.2 -r1.3
--- Log4JLogger.java 19 Apr 2006 02:38:59 -0000 1.2
+++ Log4JLogger.java 9 Feb 2007 06:57:15 -0000 1.3
@@ -13,120 +13,324 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+
+
package org.apache.commons.logging.impl;
import java.io.Serializable;
-
import org.apache.commons.logging.Log;
+import org.apache.log4j.Logger;
+import org.apache.log4j.Priority;
+import org.apache.log4j.Level;
/**
- * Implementation of Log that reflectively maps to a log4j
+ * Implementation of {@link Log} that maps directly to a
+ * <strong>Logger</strong> for log4J version 1.2.
+ * <p>
+ * Initial configuration of the corresponding Logger instances should be done
+ * in the usual manner, as outlined in the Log4J documentation.
+ * <p>
+ * The reason this logger is distinct from the 1.3 logger is that in version 1.2
+ * of Log4J:
+ * <ul>
+ * <li>class Logger takes Priority parameters not Level parameters.
+ * <li>class Level extends Priority
+ * </ul>
+ * Log4J1.3 is expected to change Level so it no longer extends Priority, which is
+ * a non-binary-compatible change. The class generated by compiling this code against
+ * log4j 1.2 will therefore not run against log4j 1.3.
*
- * @author Scott.Stark at jboss.org
- * @version $Revision: 1.2 $
+ * @author <a href="mailto:sanders at apache.org">Scott Sanders</a>
+ * @author Rod Waldhoff
+ * @author Robert Burrell Donkin
+ * @version $Id: Log4JLogger.java,v 1.3 2007/02/09 06:57:15 starksm Exp $
*/
-public class Log4JLogger implements Log, Serializable
-{
- private static final long serialVersionUID = 1;
- private Log theLogger;
- public Log4JLogger()
- {
+public class Log4JLogger implements Log, Serializable {
+
+ // ------------------------------------------------------------- Attributes
+
+ /** The fully qualified name of the Log4JLogger class. */
+ private static final String FQCN = Log4JLogger.class.getName();
+
+ /** Log to this logger */
+ private transient Logger logger = null;
+
+ /** Logger name */
+ private String name = null;
+
+ private static Priority traceLevel;
+
+ // ------------------------------------------------------------
+ // Static Initializer.
+ //
+ // Note that this must come after the static variable declarations
+ // otherwise initialiser expressions associated with those variables
+ // will override any settings done here.
+ //
+ // Verify that log4j is available, and that it is version 1.2.
+ // If an ExceptionInInitializerError is generated, then LogFactoryImpl
+ // will treat that as meaning that the appropriate underlying logging
+ // library is just not present - if discovery is in progress then
+ // discovery will continue.
+ // ------------------------------------------------------------
+
+ static {
+ if (!Priority.class.isAssignableFrom(Level.class)) {
+ // nope, this is log4j 1.3, so force an ExceptionInInitializerError
+ throw new InstantiationError("Log4J 1.2 not available");
}
- public Log4JLogger(String name)
- {
- this.theLogger = new Log4jProxy(name);
+ // Releases of log4j1.2 >= 1.2.12 have Priority.TRACE available, earlier
+ // versions do not. If TRACE is not available, then we have to map
+ // calls to Log.trace(...) onto the DEBUG level.
+
+ try {
+ traceLevel = (Priority) Level.class.getDeclaredField("TRACE").get(null);
+ } catch(Exception ex) {
+ // ok, trace not available
+ traceLevel = Priority.DEBUG;
+ }
}
- public boolean isDebugEnabled()
- {
- return theLogger.isDebugEnabled();
+
+ // ------------------------------------------------------------ Constructor
+
+ public Log4JLogger() {
}
- public boolean isErrorEnabled()
- {
- return theLogger.isErrorEnabled();
+
+ /**
+ * Base constructor.
+ */
+ public Log4JLogger(String name) {
+ this.name = name;
+ this.logger = getLogger();
}
- public boolean isFatalEnabled()
- {
- return theLogger.isFatalEnabled();
+ /** For use with a log4j factory.
+ */
+ public Log4JLogger(Logger logger ) {
+ this.name = logger.getName();
+ this.logger=logger;
}
- public boolean isInfoEnabled()
- {
- return theLogger.isInfoEnabled();
+
+ // ---------------------------------------------------------
+ // Implementation
+ //
+ // Note that in the methods below the Priority class is used to define
+ // levels even though the Level class is supported in 1.2. This is done
+ // so that at compile time the call definitely resolves to a call to
+ // a method that takes a Priority rather than one that takes a Level.
+ //
+ // The Category class (and hence its subclass Logger) in version 1.2 only
+ // has methods that take Priority objects. The Category class (and hence
+ // Logger class) in version 1.3 has methods that take both Priority and
+ // Level objects. This means that if we use Level here, and compile
+ // against log4j 1.3 then calls would be bound to the versions of
+ // methods taking Level objects and then would fail to run against
+ // version 1.2 of log4j.
+ // ---------------------------------------------------------
+
+
+ /**
+ * Logs a message with <code>org.apache.log4j.Priority.TRACE</code>.
+ * When using a log4j version that does not support the <code>TRACE</code>
+ * level, the message will be logged at the <code>DEBUG</code> level.
+ *
+ * @param message to log
+ * @see org.apache.commons.logging.Log#trace(Object)
+ */
+ public void trace(Object message) {
+ getLogger().log(FQCN, traceLevel, message, null );
}
- public boolean isTraceEnabled()
- {
- return theLogger.isTraceEnabled();
+
+ /**
+ * Logs a message with <code>org.apache.log4j.Priority.TRACE</code>.
+ * When using a log4j version that does not support the <code>TRACE</code>
+ * level, the message will be logged at the <code>DEBUG</code> level.
+ *
+ * @param message to log
+ * @param t log this cause
+ * @see org.apache.commons.logging.Log#trace(Object, Throwable)
+ */
+ public void trace(Object message, Throwable t) {
+ getLogger().log(FQCN, traceLevel, message, t );
}
- public boolean isWarnEnabled()
- {
- return theLogger.isWarnEnabled();
+
+ /**
+ * Logs a message with <code>org.apache.log4j.Priority.DEBUG</code>.
+ *
+ * @param message to log
+ * @see org.apache.commons.logging.Log#debug(Object)
+ */
+ public void debug(Object message) {
+ getLogger().log(FQCN, Priority.DEBUG, message, null );
}
- public void trace(Object message)
- {
- theLogger.trace(message);
+ /**
+ * Logs a message with <code>org.apache.log4j.Priority.DEBUG</code>.
+ *
+ * @param message to log
+ * @param t log this cause
+ * @see org.apache.commons.logging.Log#debug(Object, Throwable)
+ */
+ public void debug(Object message, Throwable t) {
+ getLogger().log(FQCN, Priority.DEBUG, message, t );
}
- public void trace(Object message, Throwable t)
- {
- theLogger.trace(message, t);
+
+ /**
+ * Logs a message with <code>org.apache.log4j.Priority.INFO</code>.
+ *
+ * @param message to log
+ * @see org.apache.commons.logging.Log#info(Object)
+ */
+ public void info(Object message) {
+ getLogger().log(FQCN, Priority.INFO, message, null );
}
- public void debug(Object message)
- {
- theLogger.debug(message);
+
+ /**
+ * Logs a message with <code>org.apache.log4j.Priority.INFO</code>.
+ *
+ * @param message to log
+ * @param t log this cause
+ * @see org.apache.commons.logging.Log#info(Object, Throwable)
+ */
+ public void info(Object message, Throwable t) {
+ getLogger().log(FQCN, Priority.INFO, message, t );
}
- public void debug(Object message, Throwable t)
- {
- theLogger.debug(message, t);
+
+ /**
+ * Logs a message with <code>org.apache.log4j.Priority.WARN</code>.
+ *
+ * @param message to log
+ * @see org.apache.commons.logging.Log#warn(Object)
+ */
+ public void warn(Object message) {
+ getLogger().log(FQCN, Priority.WARN, message, null );
}
- public void info(Object message)
- {
- theLogger.info(message);
+
+ /**
+ * Logs a message with <code>org.apache.log4j.Priority.WARN</code>.
+ *
+ * @param message to log
+ * @param t log this cause
+ * @see org.apache.commons.logging.Log#warn(Object, Throwable)
+ */
+ public void warn(Object message, Throwable t) {
+ getLogger().log(FQCN, Priority.WARN, message, t );
+ }
+
+
+ /**
+ * Logs a message with <code>org.apache.log4j.Priority.ERROR</code>.
+ *
+ * @param message to log
+ * @see org.apache.commons.logging.Log#error(Object)
+ */
+ public void error(Object message) {
+ getLogger().log(FQCN, Priority.ERROR, message, null );
+ }
+
+
+ /**
+ * Logs a message with <code>org.apache.log4j.Priority.ERROR</code>.
+ *
+ * @param message to log
+ * @param t log this cause
+ * @see org.apache.commons.logging.Log#error(Object, Throwable)
+ */
+ public void error(Object message, Throwable t) {
+ getLogger().log(FQCN, Priority.ERROR, message, t );
+ }
+
+
+ /**
+ * Logs a message with <code>org.apache.log4j.Priority.FATAL</code>.
+ *
+ * @param message to log
+ * @see org.apache.commons.logging.Log#fatal(Object)
+ */
+ public void fatal(Object message) {
+ getLogger().log(FQCN, Priority.FATAL, message, null );
}
- public void info(Object message, Throwable t)
- {
- theLogger.info(message, t);
+
+ /**
+ * Logs a message with <code>org.apache.log4j.Priority.FATAL</code>.
+ *
+ * @param message to log
+ * @param t log this cause
+ * @see org.apache.commons.logging.Log#fatal(Object, Throwable)
+ */
+ public void fatal(Object message, Throwable t) {
+ getLogger().log(FQCN, Priority.FATAL, message, t );
}
- public void warn(Object message)
- {
- theLogger.warn(message);
+
+ /**
+ * Return the native Logger instance we are using.
+ */
+ public Logger getLogger() {
+ if (logger == null) {
+ logger = Logger.getLogger(name);
}
+ return (this.logger);
+ }
+
- public void warn(Object message, Throwable t)
- {
- theLogger.warn(message, t);
+ /**
+ * Check whether the Log4j Logger used is enabled for <code>DEBUG</code> priority.
+ */
+ public boolean isDebugEnabled() {
+ return getLogger().isDebugEnabled();
}
- public void error(Object message)
- {
- theLogger.error(message);
+
+ /**
+ * Check whether the Log4j Logger used is enabled for <code>ERROR</code> priority.
+ */
+ public boolean isErrorEnabled() {
+ return getLogger().isEnabledFor(Priority.ERROR);
}
- public void error(Object message, Throwable t)
- {
- theLogger.error(message, t);
+
+ /**
+ * Check whether the Log4j Logger used is enabled for <code>FATAL</code> priority.
+ */
+ public boolean isFatalEnabled() {
+ return getLogger().isEnabledFor(Priority.FATAL);
}
- public void fatal(Object message)
- {
- theLogger.fatal(message);
+
+ /**
+ * Check whether the Log4j Logger used is enabled for <code>INFO</code> priority.
+ */
+ public boolean isInfoEnabled() {
+ return getLogger().isInfoEnabled();
}
- public void fatal(Object message, Throwable t)
- {
- theLogger.fatal(message, t);
+
+ /**
+ * Check whether the Log4j Logger used is enabled for <code>TRACE</code> priority.
+ * When using a log4j version that does not support the TRACE level, this call
+ * will report whether <code>DEBUG</code> is enabled or not.
+ */
+ public boolean isTraceEnabled() {
+ return getLogger().isEnabledFor(traceLevel);
}
+ /**
+ * Check whether the Log4j Logger used is enabled for <code>WARN</code> priority.
+ */
+ public boolean isWarnEnabled() {
+ return getLogger().isEnabledFor(Priority.WARN);
+ }
}
1.2 +303 -254 apache/commons-logging/src/java/org/apache/commons/logging/impl/Jdk14Logger.java
(In the diff below, changes in quantity of whitespace are not shown.)
Index: Jdk14Logger.java
===================================================================
RCS file: /cvsroot/jboss/apache/commons-logging/src/java/org/apache/commons/logging/impl/Jdk14Logger.java,v
retrieving revision 1.1
retrieving revision 1.2
diff -u -b -r1.1 -r1.2
--- Jdk14Logger.java 17 Apr 2006 21:00:05 -0000 1.1
+++ Jdk14Logger.java 9 Feb 2007 06:57:15 -0000 1.2
@@ -33,11 +33,18 @@
* @author <a href="mailto:sanders at apache.org">Scott Sanders</a>
* @author <a href="mailto:bloritsch at apache.org">Berin Loritsch</a>
* @author <a href="mailto:donaldp at apache.org">Peter Donald</a>
- * @version $Revision: 1.1 $ $Date: 2006/04/17 21:00:05 $
+ * @version $Revision: 1.2 $ $Date: 2007/02/09 06:57:15 $
*/
public class Jdk14Logger implements Log, Serializable {
+ /**
+ * This member variable simply ensures that any attempt to initialise
+ * this class in a pre-1.4 JVM will result in an ExceptionInInitializerError.
+ * It must not be private, as an optimising compiler could detect that it
+ * is not used and optimise it away.
+ */
+ protected static final Level dummyLevel = Level.FINE;
// ----------------------------------------------------------- Constructors
@@ -97,7 +104,10 @@
}
/**
- * Log a message with debug log level.
+ * Logs a message with <code>java.util.logging.Level.FINE</code>.
+ *
+ * @param message to log
+ * @see org.apache.commons.logging.Log#debug(Object)
*/
public void debug(Object message) {
log(Level.FINE, String.valueOf(message), null);
@@ -105,7 +115,11 @@
/**
- * Log a message and exception with debug log level.
+ * Logs a message with <code>java.util.logging.Level.FINE</code>.
+ *
+ * @param message to log
+ * @param exception log this cause
+ * @see org.apache.commons.logging.Log#debug(Object, Throwable)
*/
public void debug(Object message, Throwable exception) {
log(Level.FINE, String.valueOf(message), exception);
@@ -113,7 +127,10 @@
/**
- * Log a message with error log level.
+ * Logs a message with <code>java.util.logging.Level.SEVERE</code>.
+ *
+ * @param message to log
+ * @see org.apache.commons.logging.Log#error(Object)
*/
public void error(Object message) {
log(Level.SEVERE, String.valueOf(message), null);
@@ -121,7 +138,11 @@
/**
- * Log a message and exception with error log level.
+ * Logs a message with <code>java.util.logging.Level.SEVERE</code>.
+ *
+ * @param message to log
+ * @param exception log this cause
+ * @see org.apache.commons.logging.Log#error(Object, Throwable)
*/
public void error(Object message, Throwable exception) {
log(Level.SEVERE, String.valueOf(message), exception);
@@ -129,7 +150,10 @@
/**
- * Log a message with fatal log level.
+ * Logs a message with <code>java.util.logging.Level.SEVERE</code>.
+ *
+ * @param message to log
+ * @see org.apache.commons.logging.Log#fatal(Object)
*/
public void fatal(Object message) {
log(Level.SEVERE, String.valueOf(message), null);
@@ -137,7 +161,11 @@
/**
- * Log a message and exception with fatal log level.
+ * Logs a message with <code>java.util.logging.Level.SEVERE</code>.
+ *
+ * @param message to log
+ * @param exception log this cause
+ * @see org.apache.commons.logging.Log#fatal(Object, Throwable)
*/
public void fatal(Object message, Throwable exception) {
log(Level.SEVERE, String.valueOf(message), exception);
@@ -156,7 +184,10 @@
/**
- * Log a message with info log level.
+ * Logs a message with <code>java.util.logging.Level.INFO</code>.
+ *
+ * @param message to log
+ * @see org.apache.commons.logging.Log#info(Object)
*/
public void info(Object message) {
log(Level.INFO, String.valueOf(message), null);
@@ -164,7 +195,11 @@
/**
- * Log a message and exception with info log level.
+ * Logs a message with <code>java.util.logging.Level.INFO</code>.
+ *
+ * @param message to log
+ * @param exception log this cause
+ * @see org.apache.commons.logging.Log#info(Object, Throwable)
*/
public void info(Object message, Throwable exception) {
log(Level.INFO, String.valueOf(message), exception);
@@ -220,7 +255,10 @@
/**
- * Log a message with trace log level.
+ * Logs a message with <code>java.util.logging.Level.FINEST</code>.
+ *
+ * @param message to log
+ * @see org.apache.commons.logging.Log#trace(Object)
*/
public void trace(Object message) {
log(Level.FINEST, String.valueOf(message), null);
@@ -228,7 +266,11 @@
/**
- * Log a message and exception with trace log level.
+ * Logs a message with <code>java.util.logging.Level.FINEST</code>.
+ *
+ * @param message to log
+ * @param exception log this cause
+ * @see org.apache.commons.logging.Log#trace(Object, Throwable)
*/
public void trace(Object message, Throwable exception) {
log(Level.FINEST, String.valueOf(message), exception);
@@ -236,7 +278,10 @@
/**
- * Log a message with warn log level.
+ * Logs a message with <code>java.util.logging.Level.WARNING</code>.
+ *
+ * @param message to log
+ * @see org.apache.commons.logging.Log#warn(Object)
*/
public void warn(Object message) {
log(Level.WARNING, String.valueOf(message), null);
@@ -244,7 +289,11 @@
/**
- * Log a message and exception with warn log level.
+ * Logs a message with <code>java.util.logging.Level.WARNING</code>.
+ *
+ * @param message to log
+ * @param exception log this cause
+ * @see org.apache.commons.logging.Log#warn(Object, Throwable)
*/
public void warn(Object message, Throwable exception) {
log(Level.WARNING, String.valueOf(message), exception);
1.2 +293 -251 apache/commons-logging/src/java/org/apache/commons/logging/impl/LogKitLogger.java
(In the diff below, changes in quantity of whitespace are not shown.)
Index: LogKitLogger.java
===================================================================
RCS file: /cvsroot/jboss/apache/commons-logging/src/java/org/apache/commons/logging/impl/LogKitLogger.java,v
retrieving revision 1.1
retrieving revision 1.2
diff -u -b -r1.1 -r1.2
--- LogKitLogger.java 17 Apr 2006 21:00:05 -0000 1.1
+++ LogKitLogger.java 9 Feb 2007 06:57:15 -0000 1.2
@@ -34,7 +34,7 @@
*
* @author <a href="mailto:sanders at apache.org">Scott Sanders</a>
* @author Robert Burrell Donkin
- * @version $Id: LogKitLogger.java,v 1.1 2006/04/17 21:00:05 starksm Exp $
+ * @version $Id: LogKitLogger.java,v 1.2 2007/02/09 06:57:15 starksm Exp $
*/
public class LogKitLogger implements Log, Serializable {
@@ -85,7 +85,10 @@
/**
- * Log message to <code>LogKit</code> logger with <code>DEBUG</code> priority.
+ * Logs a message with <code>org.apache.log.Priority.DEBUG</code>.
+ *
+ * @param message to log
+ * @see org.apache.commons.logging.Log#trace(Object)
*/
public void trace(Object message) {
debug(message);
@@ -93,7 +96,11 @@
/**
- * Log error to <code>LogKit</code> logger with <code>DEBUG</code> priority.
+ * Logs a message with <code>org.apache.log.Priority.DEBUG</code>.
+ *
+ * @param message to log
+ * @param t log this cause
+ * @see org.apache.commons.logging.Log#trace(Object, Throwable)
*/
public void trace(Object message, Throwable t) {
debug(message, t);
@@ -101,7 +108,10 @@
/**
- * Log message to <code>LogKit</code> logger with <code>DEBUG</code> priority.
+ * Logs a message with <code>org.apache.log.Priority.DEBUG</code>.
+ *
+ * @param message to log
+ * @see org.apache.commons.logging.Log#debug(Object)
*/
public void debug(Object message) {
if (message != null) {
@@ -111,7 +121,11 @@
/**
- * Log error to <code>LogKit</code> logger with <code>DEBUG</code> priority.
+ * Logs a message with <code>org.apache.log.Priority.DEBUG</code>.
+ *
+ * @param message to log
+ * @param t log this cause
+ * @see org.apache.commons.logging.Log#debug(Object, Throwable)
*/
public void debug(Object message, Throwable t) {
if (message != null) {
@@ -121,7 +135,10 @@
/**
- * Log message to <code>LogKit</code> logger with <code>INFO</code> priority.
+ * Logs a message with <code>org.apache.log.Priority.INFO</code>.
+ *
+ * @param message to log
+ * @see org.apache.commons.logging.Log#info(Object)
*/
public void info(Object message) {
if (message != null) {
@@ -131,7 +148,11 @@
/**
- * Log error to <code>LogKit</code> logger with <code>INFO</code> priority.
+ * Logs a message with <code>org.apache.log.Priority.INFO</code>.
+ *
+ * @param message to log
+ * @param t log this cause
+ * @see org.apache.commons.logging.Log#info(Object, Throwable)
*/
public void info(Object message, Throwable t) {
if (message != null) {
@@ -141,7 +162,10 @@
/**
- * Log message to <code>LogKit</code> logger with <code>WARN</code> priority.
+ * Logs a message with <code>org.apache.log.Priority.WARN</code>.
+ *
+ * @param message to log
+ * @see org.apache.commons.logging.Log#warn(Object)
*/
public void warn(Object message) {
if (message != null) {
@@ -151,7 +175,11 @@
/**
- * Log error to <code>LogKit</code> logger with <code>WARN</code> priority.
+ * Logs a message with <code>org.apache.log.Priority.WARN</code>.
+ *
+ * @param message to log
+ * @param t log this cause
+ * @see org.apache.commons.logging.Log#warn(Object, Throwable)
*/
public void warn(Object message, Throwable t) {
if (message != null) {
@@ -161,7 +189,10 @@
/**
- * Log message to <code>LogKit</code> logger with <code>ERROR</code> priority.
+ * Logs a message with <code>org.apache.log.Priority.ERROR</code>.
+ *
+ * @param message to log
+ * @see org.apache.commons.logging.Log#error(Object)
*/
public void error(Object message) {
if (message != null) {
@@ -171,7 +202,11 @@
/**
- * Log error to <code>LogKit</code> logger with <code>ERROR</code> priority.
+ * Logs a message with <code>org.apache.log.Priority.ERROR</code>.
+ *
+ * @param message to log
+ * @param t log this cause
+ * @see org.apache.commons.logging.Log#error(Object, Throwable)
*/
public void error(Object message, Throwable t) {
if (message != null) {
@@ -181,7 +216,10 @@
/**
- * Log message to <code>LogKit</code> logger with <code>FATAL_ERROR</code> priority.
+ * Logs a message with <code>org.apache.log.Priority.FATAL_ERROR</code>.
+ *
+ * @param message to log
+ * @see org.apache.commons.logging.Log#fatal(Object)
*/
public void fatal(Object message) {
if (message != null) {
@@ -191,7 +229,11 @@
/**
- * Log error to <code>LogKit</code> logger with <code>FATAL_ERROR</code> priority.
+ * Logs a message with <code>org.apache.log.Priority.FATAL_ERROR</code>.
+ *
+ * @param message to log
+ * @param t log this cause
+ * @see org.apache.commons.logging.Log#fatal(Object, Throwable)
*/
public void fatal(Object message, Throwable t) {
if (message != null) {
@@ -201,7 +243,7 @@
/**
- * Check whether the <code>LogKit</code> logger will log messages of priority <code>DEBUG</code>.
+ * Checks whether the <code>LogKit</code> logger will log messages of priority <code>DEBUG</code>.
*/
public boolean isDebugEnabled() {
return getLogger().isDebugEnabled();
@@ -209,7 +251,7 @@
/**
- * Check whether the <code>LogKit</code> logger will log messages of priority <code>ERROR</code>.
+ * Checks whether the <code>LogKit</code> logger will log messages of priority <code>ERROR</code>.
*/
public boolean isErrorEnabled() {
return getLogger().isErrorEnabled();
@@ -217,7 +259,7 @@
/**
- * Check whether the <code>LogKit</code> logger will log messages of priority <code>FATAL_ERROR</code>.
+ * Checks whether the <code>LogKit</code> logger will log messages of priority <code>FATAL_ERROR</code>.
*/
public boolean isFatalEnabled() {
return getLogger().isFatalErrorEnabled();
@@ -225,7 +267,7 @@
/**
- * Check whether the <code>LogKit</code> logger will log messages of priority <code>INFO</code>.
+ * Checks whether the <code>LogKit</code> logger will log messages of priority <code>INFO</code>.
*/
public boolean isInfoEnabled() {
return getLogger().isInfoEnabled();
@@ -233,7 +275,7 @@
/**
- * Check whether the <code>LogKit</code> logger will log messages of priority <code>DEBUG</code>.
+ * Checks whether the <code>LogKit</code> logger will log messages of priority <code>DEBUG</code>.
*/
public boolean isTraceEnabled() {
return getLogger().isDebugEnabled();
@@ -241,7 +283,7 @@
/**
- * Check whether the <code>LogKit</code> logger will log messages of priority <code>WARN</code>.
+ * Checks whether the <code>LogKit</code> logger will log messages of priority <code>WARN</code>.
*/
public boolean isWarnEnabled() {
return getLogger().isWarnEnabled();
1.1 date: 2007/02/09 06:57:15; author: starksm; state: Exp;apache/commons-logging/src/java/org/apache/commons/logging/impl/WeakHashtable.java
Index: WeakHashtable.java
===================================================================
/*
* Copyright 2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.logging.impl;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.WeakReference;
import java.util.*;
/**
* <p>Implementation of <code>Hashtable</code> that uses <code>WeakReference</code>'s
* to hold its keys thus allowing them to be reclaimed by the garbage collector.
* The associated values are retained using strong references.</p>
*
* <p>This class follows the symantics of <code>Hashtable</code> as closely as
* possible. It therefore does not accept null values or keys.</p>
*
* <p><strong>Note:</strong>
* This is <em>not</em> intended to be a general purpose hash table replacement.
* This implementation is also tuned towards a particular purpose: for use as a replacement
* for <code>Hashtable</code> in <code>LogFactory</code>. This application requires
* good liveliness for <code>get</code> and <code>put</code>. Various tradeoffs
* have been made with this in mind.
* </p>
* <p>
* <strong>Usage:</strong> typical use case is as a drop-in replacement
* for the <code>Hashtable</code> used in <code>LogFactory</code> for J2EE enviroments
* running 1.3+ JVMs. Use of this class <i>in most cases</i> (see below) will
* allow classloaders to be collected by the garbage collector without the need
* to call {@link org.apache.commons.logging.LogFactory#release(ClassLoader) LogFactory.release(ClassLoader)}.
* </p>
*
* <p><code>org.apache.commons.logging.LogFactory</code> checks whether this class
* can be supported by the current JVM, and if so then uses it to store
* references to the <code>LogFactory</code> implementationd it loads
* (rather than using a standard Hashtable instance).
* Having this class used instead of <code>Hashtable</code> solves
* certain issues related to dynamic reloading of applications in J2EE-style
* environments. However this class requires java 1.3 or later (due to its use
* of <code>java.lang.ref.WeakReference</code> and associates).
* And by the way, this extends <code>Hashtable</code> rather than <code>HashMap</code>
* for backwards compatibility reasons. See the documentation
* for method <code>LogFactory.createFactoryStore</code> for more details.</p>
*
* <p>The reason all this is necessary is due to a issue which
* arises during hot deploy in a J2EE-like containers.
* Each component running in the container owns one or more classloaders; when
* the component loads a LogFactory instance via the component classloader
* a reference to it gets stored in the static LogFactory.factories member,
* keyed by the component's classloader so different components don't
* stomp on each other. When the component is later unloaded, the container
* sets the component's classloader to null with the intent that all the
* component's classes get garbage-collected. However there's still a
* reference to the component's classloader from a key in the "global"
* <code>LogFactory</code>'s factories member! If <code>LogFactory.release()</code>
* is called whenever component is unloaded, the classloaders will be correctly
* garbage collected; this <i>should</i> be done by any container that
* bundles commons-logging by default. However, holding the classloader
* references weakly ensures that the classloader will be garbage collected
* without the container performing this step. </p>
*
* <p>
* <strong>Limitations:</strong>
* There is still one (unusual) scenario in which a component will not
* be correctly unloaded without an explicit release. Though weak references
* are used for its keys, it is necessary to use strong references for its values.
* </p>
*
* <p> If the abstract class <code>LogFactory</code> is
* loaded by the container classloader but a subclass of
* <code>LogFactory</code> [LogFactory1] is loaded by the component's
* classloader and an instance stored in the static map associated with the
* base LogFactory class, then there is a strong reference from the LogFactory
* class to the LogFactory1 instance (as normal) and a strong reference from
* the LogFactory1 instance to the component classloader via
* <code>getClass().getClassLoader()</code>. This chain of references will prevent
* collection of the child classloader.</p>
*
* <p>
* Such a situation occurs when the commons-logging.jar is
* loaded by a parent classloader (e.g. a server level classloader in a
* servlet container) and a custom <code>LogFactory</code> implementation is
* loaded by a child classloader (e.g. a web app classloader).</p>
*
* <p>To avoid this scenario, ensure
* that any custom LogFactory subclass is loaded by the same classloader as
* the base <code>LogFactory</code>. Creating custom LogFactory subclasses is,
* however, rare. The standard LogFactoryImpl class should be sufficient
* for most or all users.</p>
*
*
* @author Brian Stansberry
*
* @since 1.1
*/
public final class WeakHashtable extends Hashtable {
/**
* The maximum number of times put() or remove() can be called before
* the map will be purged of all cleared entries.
*/
private static final int MAX_CHANGES_BEFORE_PURGE = 100;
/**
* The maximum number of times put() or remove() can be called before
* the map will be purged of one cleared entry.
*/
private static final int PARTIAL_PURGE_COUNT = 10;
/* ReferenceQueue we check for gc'd keys */
private ReferenceQueue queue = new ReferenceQueue();
/* Counter used to control how often we purge gc'd entries */
private int changeCount = 0;
/**
* Constructs a WeakHashtable with the Hashtable default
* capacity and load factor.
*/
public WeakHashtable() {}
/**
*@see Hashtable
*/
public boolean containsKey(Object key) {
// purge should not be required
Referenced referenced = new Referenced(key);
return super.containsKey(referenced);
}
/**
*@see Hashtable
*/
public Enumeration elements() {
purge();
return super.elements();
}
/**
*@see Hashtable
*/
public Set entrySet() {
purge();
Set referencedEntries = super.entrySet();
Set unreferencedEntries = new HashSet();
for (Iterator it=referencedEntries.iterator(); it.hasNext();) {
Map.Entry entry = (Map.Entry) it.next();
Referenced referencedKey = (Referenced) entry.getKey();
Object key = referencedKey.getValue();
Object value = entry.getValue();
if (key != null) {
Entry dereferencedEntry = new Entry(key, value);
unreferencedEntries.add(dereferencedEntry);
}
}
return unreferencedEntries;
}
/**
*@see Hashtable
*/
public Object get(Object key) {
// for performance reasons, no purge
Referenced referenceKey = new Referenced(key);
return super.get(referenceKey);
}
/**
*@see Hashtable
*/
public Enumeration keys() {
purge();
final Enumeration enumer = super.keys();
return new Enumeration() {
public boolean hasMoreElements() {
return enumer.hasMoreElements();
}
public Object nextElement() {
Referenced nextReference = (Referenced) enumer.nextElement();
return nextReference.getValue();
}
};
}
/**
*@see Hashtable
*/
public Set keySet() {
purge();
Set referencedKeys = super.keySet();
Set unreferencedKeys = new HashSet();
for (Iterator it=referencedKeys.iterator(); it.hasNext();) {
Referenced referenceKey = (Referenced) it.next();
Object keyValue = referenceKey.getValue();
if (keyValue != null) {
unreferencedKeys.add(keyValue);
}
}
return unreferencedKeys;
}
/**
*@see Hashtable
*/
public Object put(Object key, Object value) {
// check for nulls, ensuring symantics match superclass
if (key == null) {
throw new NullPointerException("Null keys are not allowed");
}
if (value == null) {
throw new NullPointerException("Null values are not allowed");
}
// for performance reasons, only purge every
// MAX_CHANGES_BEFORE_PURGE times
if (changeCount++ > MAX_CHANGES_BEFORE_PURGE) {
purge();
changeCount = 0;
}
// do a partial purge more often
else if ((changeCount % PARTIAL_PURGE_COUNT) == 0) {
purgeOne();
}
Object result = null;
Referenced keyRef = new Referenced(key, queue);
return super.put(keyRef, value);
}
/**
*@see Hashtable
*/
public void putAll(Map t) {
if (t != null) {
Set entrySet = t.entrySet();
for (Iterator it=entrySet.iterator(); it.hasNext();) {
Map.Entry entry = (Map.Entry) it.next();
put(entry.getKey(), entry.getValue());
}
}
}
/**
*@see Hashtable
*/
public Collection values() {
purge();
return super.values();
}
/**
*@see Hashtable
*/
public Object remove(Object key) {
// for performance reasons, only purge every
// MAX_CHANGES_BEFORE_PURGE times
if (changeCount++ > MAX_CHANGES_BEFORE_PURGE) {
purge();
changeCount = 0;
}
// do a partial purge more often
else if ((changeCount % PARTIAL_PURGE_COUNT) == 0) {
purgeOne();
}
return super.remove(new Referenced(key));
}
/**
*@see Hashtable
*/
public boolean isEmpty() {
purge();
return super.isEmpty();
}
/**
*@see Hashtable
*/
public int size() {
purge();
return super.size();
}
/**
*@see Hashtable
*/
public String toString() {
purge();
return super.toString();
}
/**
* @see Hashtable
*/
protected void rehash() {
// purge here to save the effort of rehashing dead entries
purge();
super.rehash();
}
/**
* Purges all entries whose wrapped keys
* have been garbage collected.
*/
private void purge() {
synchronized (queue) {
WeakKey key;
while ((key = (WeakKey) queue.poll()) != null) {
super.remove(key.getReferenced());
}
}
}
/**
* Purges one entry whose wrapped key
* has been garbage collected.
*/
private void purgeOne() {
synchronized (queue) {
WeakKey key = (WeakKey) queue.poll();
if (key != null) {
super.remove(key.getReferenced());
}
}
}
/** Entry implementation */
private final static class Entry implements Map.Entry {
private final Object key;
private final Object value;
private Entry(Object key, Object value) {
this.key = key;
this.value = value;
}
public boolean equals(Object o) {
boolean result = false;
if (o != null && o instanceof Map.Entry) {
Map.Entry entry = (Map.Entry) o;
result = (getKey()==null ?
entry.getKey() == null :
getKey().equals(entry.getKey()))
&&
(getValue()==null ?
entry.getValue() == null :
getValue().equals(entry.getValue()));
}
return result;
}
public int hashCode() {
return (getKey()==null ? 0 : getKey().hashCode()) ^
(getValue()==null ? 0 : getValue().hashCode());
}
public Object setValue(Object value) {
throw new UnsupportedOperationException("Entry.setValue is not supported.");
}
public Object getValue() {
return value;
}
public Object getKey() {
return key;
}
}
/** Wrapper giving correct symantics for equals and hashcode */
private final static class Referenced {
private final WeakReference reference;
private final int hashCode;
/**
*
* @throws NullPointerException if referant is <code>null</code>
*/
private Referenced(Object referant) {
reference = new WeakReference(referant);
// Calc a permanent hashCode so calls to Hashtable.remove()
// work if the WeakReference has been cleared
hashCode = referant.hashCode();
}
/**
*
* @throws NullPointerException if key is <code>null</code>
*/
private Referenced(Object key, ReferenceQueue queue) {
reference = new WeakKey(key, queue, this);
// Calc a permanent hashCode so calls to Hashtable.remove()
// work if the WeakReference has been cleared
hashCode = key.hashCode();
}
public int hashCode() {
return hashCode;
}
private Object getValue() {
return reference.get();
}
public boolean equals(Object o) {
boolean result = false;
if (o instanceof Referenced) {
Referenced otherKey = (Referenced) o;
Object thisKeyValue = getValue();
Object otherKeyValue = otherKey.getValue();
if (thisKeyValue == null) {
result = (otherKeyValue == null);
// Since our hashcode was calculated from the original
// non-null referant, the above check breaks the
// hashcode/equals contract, as two cleared Referenced
// objects could test equal but have different hashcodes.
// We can reduce (not eliminate) the chance of this
// happening by comparing hashcodes.
if (result == true) {
result = (this.hashCode() == otherKey.hashCode());
}
// In any case, as our c'tor does not allow null referants
// and Hashtable does not do equality checks between
// existing keys, normal hashtable operations should never
// result in an equals comparison between null referants
}
else
{
result = thisKeyValue.equals(otherKeyValue);
}
}
return result;
}
}
/**
* WeakReference subclass that holds a hard reference to an
* associated <code>value</code> and also makes accessible
* the Referenced object holding it.
*/
private final static class WeakKey extends WeakReference {
private final Referenced referenced;
private WeakKey(Object key,
ReferenceQueue queue,
Referenced referenced) {
super(key, queue);
this.referenced = referenced;
}
private Referenced getReferenced() {
return referenced;
}
}
}
1.1 date: 2007/02/09 06:57:15; author: starksm; state: Exp;apache/commons-logging/src/java/org/apache/commons/logging/impl/ServletContextCleaner.java
Index: ServletContextCleaner.java
===================================================================
/*
* Copyright 2005 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.logging.impl;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import org.apache.commons.logging.LogFactory;
/**
* This class is capable of receiving notifications about the undeployment of
* a webapp, and responds by ensuring that commons-logging releases all
* memory associated with the undeployed webapp.
* <p>
* In general, the WeakHashtable support added in commons-logging release 1.1
* ensures that logging classes do not hold references that prevent an
* undeployed webapp's memory from being garbage-collected even when multiple
* copies of commons-logging are deployed via multiple classloaders (a
* situation that earlier versions had problems with). However there are
* some rare cases where the WeakHashtable approach does not work; in these
* situations specifying this class as a listener for the web application will
* ensure that all references held by commons-logging are fully released.
* <p>
* To use this class, configure the webapp deployment descriptor to call
* this class on webapp undeploy; the contextDestroyed method will tell
* every accessable LogFactory class that the entry in its map for the
* current webapp's context classloader should be cleared.
*
* @since 1.1
*/
public class ServletContextCleaner implements ServletContextListener {
private Class[] RELEASE_SIGNATURE = {ClassLoader.class};
/**
* Invoked when a webapp is undeployed, this tells the LogFactory
* class to release any logging information related to the current
* contextClassloader.
*/
public void contextDestroyed(ServletContextEvent sce) {
ClassLoader tccl = Thread.currentThread().getContextClassLoader();
Object[] params = new Object[1];
params[0] = tccl;
// Walk up the tree of classloaders, finding all the available
// LogFactory classes and releasing any objects associated with
// the tccl (ie the webapp).
//
// When there is only one LogFactory in the classpath, and it
// is within the webapp being undeployed then there is no problem;
// garbage collection works fine.
//
// When there are multiple LogFactory classes in the classpath but
// parent-first classloading is used everywhere, this loop is really
// short. The first instance of LogFactory found will
// be the highest in the classpath, and then no more will be found.
// This is ok, as with this setup this will be the only LogFactory
// holding any data associated with the tccl being released.
//
// When there are multiple LogFactory classes in the classpath and
// child-first classloading is used in any classloader, then multiple
// LogFactory instances may hold info about this TCCL; whenever the
// webapp makes a call into a class loaded via an ancestor classloader
// and that class calls LogFactory the tccl gets registered in
// the LogFactory instance that is visible from the ancestor
// classloader. However the concrete logging library it points
// to is expected to have been loaded via the TCCL, so the
// underlying logging lib is only initialised/configured once.
// These references from ancestor LogFactory classes down to
// TCCL classloaders are held via weak references and so should
// be released but there are circumstances where they may not.
// Walking up the classloader ancestry ladder releasing
// the current tccl at each level tree, though, will definitely
// clear any problem references.
ClassLoader loader = tccl;
while (loader != null) {
// Load via the current loader. Note that if the class is not accessable
// via this loader, but is accessable via some ancestor then that class
// will be returned.
try {
Class logFactoryClass = loader.loadClass("org.apache.commons.logging.LogFactory");
Method releaseMethod = logFactoryClass.getMethod("release", RELEASE_SIGNATURE);
releaseMethod.invoke(null, params);
loader = logFactoryClass.getClassLoader().getParent();
} catch(ClassNotFoundException ex) {
// Neither the current classloader nor any of its ancestors could find
// the LogFactory class, so we can stop now.
loader = null;
} catch(NoSuchMethodException ex) {
// This is not expected; every version of JCL has this method
System.err.println("LogFactory instance found which does not support release method!");
loader = null;
} catch(IllegalAccessException ex) {
// This is not expected; every ancestor class should be accessable
System.err.println("LogFactory instance found which is not accessable!");
loader = null;
} catch(InvocationTargetException ex) {
// This is not expected
System.err.println("LogFactory instance release method failed!");
loader = null;
}
}
// Just to be sure, invoke release on the LogFactory that is visible from
// this ServletContextCleaner class too. This should already have been caught
// by the above loop but just in case...
LogFactory.release(tccl);
}
/**
* Invoked when a webapp is deployed. Nothing needs to be done here.
*/
public void contextInitialized(ServletContextEvent sce) {
// do nothing
}
}
More information about the jboss-cvs-commits
mailing list