From 15956fee8248c4b2d8dacd1d088cfa20eb6f43e9 Mon Sep 17 00:00:00 2001
From: Simon Kitching This factory will remember previously created
- * This method looks in the following places:
- * Log instances
* for the same name, and will return them on repeated requests to the
- * getInstance() method. This implementation ignores any
- * configured attributes.getInstance() method.
*
* @author Rod Waldhoff
* @author Craig R. McClanahan
* @author Richard A. Sitze
+ * @author Brian Stansberry
* @version $Revision$ $Date$
*/
@@ -115,6 +115,7 @@ public class LogFactoryImpl extends LogFactory {
*/
private String diagnosticPrefix;
+
/**
* Configuration attributes.
*/
@@ -164,9 +165,9 @@ public class LogFactoryImpl extends LogFactory {
protected Class logMethodSignature[] =
{ LogFactory.class };
-
// --------------------------------------------------------- Public Methods
+
/**
* Return the configuration attribute with the specified name (if any),
* or null if there is no such attribute.
@@ -309,14 +310,16 @@ public class LogFactoryImpl extends LogFactory {
return LogFactory.getContextClassLoader();
}
+
/**
* Workaround for bug in Java1.2; in theory this method is not needed.
- * See LogFactory.isInternalLoggingEnabled.
+ * See LogFactory.isDiagnosticsEnabled.
*/
protected static boolean isDiagnosticsEnabled() {
return LogFactory.isDiagnosticsEnabled();
}
+
/**
* Workaround for bug in Java1.2; in theory this method is not needed.
* See LogFactory.getClassLoader.
@@ -325,6 +328,7 @@ public class LogFactoryImpl extends LogFactory {
return LogFactory.getClassLoader(clazz);
}
+
// ------------------------------------------------------ Protected Methods
/**
@@ -352,6 +356,7 @@ public class LogFactoryImpl extends LogFactory {
diagnosticPrefix = clazz.getName() + "@" + classLoader.toString() + ":";
}
+
/**
* Output a diagnostic message to a user-specified destination (if the
* user has enabled diagnostic logging).
@@ -366,75 +371,18 @@ public class LogFactoryImpl extends LogFactory {
/**
* Return the fully qualified Java classname of the {@link Log}
- * implementation we will be using.
- *
- *
+ * implementation we will be using.
+ *
+ * @deprecated Never invoked by this class; subclasses should not assume
+ * it will be.
*/
protected String getLogClassName() {
- // Return the previously identified class name (if any)
- if (logClassName != null) {
- return logClassName;
- }
-
- logDiagnostic("Determining the name for the Log implementation.");
-
- logDiagnostic("Trying to get log class from attribute " + LOG_PROPERTY);
- logClassName = (String) getAttribute(LOG_PROPERTY);
-
- if (logClassName == null) { // @deprecated
- logDiagnostic("Trying to get log class from attribute " + LOG_PROPERTY_OLD);
- logClassName = (String) getAttribute(LOG_PROPERTY_OLD);
- }
-
if (logClassName == null) {
- try {
- logDiagnostic("Trying to get log class from system property " + LOG_PROPERTY);
- logClassName = System.getProperty(LOG_PROPERTY);
- } catch (SecurityException e) {
- ;
- }
+ discoverLogImplementation(getClass().getName());
}
-
- if (logClassName == null) { // @deprecated
- try {
- logDiagnostic("Trying to get log class from system property " + LOG_PROPERTY_OLD);
- logClassName = System.getProperty(LOG_PROPERTY_OLD);
- } catch (SecurityException e) {
- ;
- }
- }
-
- // no need for internalLog calls below; they are done inside the
- // various isXXXAvailable methods.
- if ((logClassName == null) && isLog4JAvailable()) {
- logClassName = "org.apache.commons.logging.impl.Log4JLogger";
- }
-
- if ((logClassName == null) && isJdk14Available()) {
- logClassName = "org.apache.commons.logging.impl.Jdk14Logger";
- }
-
- if ((logClassName == null) && isJdk13LumberjackAvailable()) {
- logClassName = "org.apache.commons.logging.impl.Jdk13LumberjackLogger";
- }
-
- if (logClassName == null) {
- logClassName = "org.apache.commons.logging.impl.SimpleLog";
- }
-
- logDiagnostic("Using log class " + logClassName);
- return (logClassName);
-
+
+ return logClassName;
}
@@ -448,138 +396,23 @@ public class LogFactoryImpl extends LogFactory {
* in all circumstances.
setLogFactory method (if there is one)
- try {
- logMethod = logClass.getMethod("setLogFactory",
- logMethodSignature);
- } catch (Throwable t) {
- logMethod = null;
- }
-
- // 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);
- }
+ return logConstructor;
}
+
- /**
- * Report a problem loading the log adapter, then always throw
- * a LogConfigurationException.
- * - * There are two possible reasons why we successfully loaded the - * specified log adapter class then failed to cast it to a Log object: - *
- * Here we try to figure out which case has occurred so we can give the - * user some reasonable feedback. - * - * @param logInterface is the class that this LogFactoryImpl class needs - * to return the adapter as. - * @param logClass is the adapter class we successfully loaded (but which - * could not be cast to type logInterface). - */ - private LogConfigurationException reportInvalidLogAdapter( - Class logInterface, Class logClass) { - - Class interfaces[] = logClass.getInterfaces(); - for (int i = 0; i < interfaces.length; i++) { - if (LOG_INTERFACE.equals(interfaces[i].getName())) { - - if (isDiagnosticsEnabled()) { - ClassLoader logInterfaceClassLoader = getClassLoader(logInterface); - ClassLoader logAdapterClassLoader = getClassLoader(logClass); - Class logAdapterInterface = interfaces[i]; - ClassLoader logAdapterInterfaceClassLoader = getClassLoader(logAdapterInterface); - logDiagnostic( - "Class " + logClassName + " was found in classloader " - + objectId(logAdapterClassLoader) - + " but it implements the Log interface as loaded" - + " from classloader " + objectId(logAdapterInterfaceClassLoader) - + " not the one loaded by this class's classloader " - + objectId(logInterfaceClassLoader)); - } - - throw new LogConfigurationException - ("Invalid class loader hierarchy. " + - "You have more than one version of '" + - LOG_INTERFACE + "' visible, which is " + - "not allowed."); - } - } - - return new LogConfigurationException - ("Class " + logClassName + " does not implement '" + - LOG_INTERFACE + "'."); - } - /** * MUST KEEP THIS METHOD PRIVATE. * @@ -590,10 +423,14 @@ public class LogFactoryImpl extends LogFactory { *
* * Load a class, try first the thread class loader, and - * if it fails use the loader that loaded this class. Actually, as - * the thread (context) classloader should always be the same as or a - * child of the classloader that loaded this class, the fallback should - * never be used. + * if it fails use the loader that loaded this class. + * + * @param name fully qualified class name of the class to load + * + * @throws LinkageError if the linkage fails + * @throws ExceptionInInitializerError if the initialization provoked + * by this method fails + * @throws ClassNotFoundException if the class cannot be located */ private static Class loadClass( final String name ) throws ClassNotFoundException @@ -619,29 +456,32 @@ public class LogFactoryImpl extends LogFactory { if (result instanceof Class) return (Class)result; - + throw (ClassNotFoundException)result; } /** - * Is JDK 1.3 with Lumberjack logging available? + * Is JDK 1.3 with Lumberjack logging available? + * + * @deprecated Never invoked by this class; subclasses should not assume + * it will be. */ protected boolean isJdk13LumberjackAvailable() { - - // note: the algorithm here is different from isLog4JAvailable. - // I think isLog4JAvailable is correct....see bugzilla#31597 + logDiagnostic("Checking for Jdk13Lumberjack."); try { - loadClass("java.util.logging.Logger"); - loadClass("org.apache.commons.logging.impl.Jdk13LumberjackLogger"); + createLogFromClass("org.apache.commons.logging.impl.Jdk13LumberjackLogger", + getClass().getName(), + false); + // No exception means success logDiagnostic("Found Jdk13Lumberjack."); return true; } catch (Throwable t) { logDiagnostic("Did not find Jdk13Lumberjack."); return false; } - + } @@ -649,20 +489,19 @@ public class LogFactoryImpl extends LogFactory { *Return true if JDK 1.4 or later logging
* is available. Also checks that the Throwable class
* supports getStackTrace(), which is required by
- * Jdk14Logger.
null
+ */
+ private String findUserSpecifiedLogClassName()
+ {
+ logDiagnostic("Trying to get log class from attribute " + LOG_PROPERTY);
+ String specifiedClass = (String) getAttribute(LOG_PROPERTY);
+
+ if (specifiedClass == null) { // @deprecated
+ logDiagnostic("Trying to get log class from attribute " +
+ LOG_PROPERTY_OLD);
+ specifiedClass = (String) getAttribute(LOG_PROPERTY_OLD);
+ }
+
+ if (specifiedClass == null) {
+ logDiagnostic("Trying to get log class from system property " +
+ LOG_PROPERTY);
+ try {
+ specifiedClass = System.getProperty(LOG_PROPERTY);
+ } catch (SecurityException e) {
+ ;
+ }
+ }
+
+ if (specifiedClass == null) { // @deprecated
+ logDiagnostic("Trying to get log class from system property " +
+ LOG_PROPERTY_OLD);
+ try {
+ specifiedClass = System.getProperty(LOG_PROPERTY_OLD);
+ } catch (SecurityException e) {
+ ;
+ }
+ }
+
+ return specifiedClass;
+
}
+
+ /**
+ * Attempts to load the given class, find a suitable constructor,
+ * and instantiate an instance of Log.
+ *
+ * @param logAdapterClass classname of the Log implementation
+ * @param logCategory argument to pass to the Log implementation's
+ * constructor
+ * @param affectState true if this object's state should
+ * be affected by this method call, false
+ * otherwise.
+ *
+ * @return an instance of the given class. Will not return
+ * null.
+ *
+ * @throws LinkageError if any linkage provoked by this method fails
+ * @throws ExceptionInInitializerError if any initialization provoked
+ * by this method fails
+ * @throws ClassNotFoundException if the class cannot be located
+ * @throws NoClassDefFoundError if logImplClass could be
+ * loaded but the logging implementation it
+ * relies on could not be located
+ * @throws LogConfigurationException if the class was loaded but no suitable
+ * logger could be created and this object
+ * is configured to fail in such a
+ * situation
+ */
+ private Log createLogFromClass(String logAdapterClass,
+ String logCategory,
+ boolean affectState)
+ throws Throwable {
+
+ logDiagnostic("Attempting to instantiate " + logAdapterClass);
+
+ Class logClass = loadClass(logAdapterClass);
+
+ Object[] params = { logCategory };
+ Log result = null;
+ Constructor constructor = null;
+ try {
+ constructor = logClass.getConstructor(logConstructorSignature);
+ result = (Log) constructor.newInstance(params);
+ } catch (NoClassDefFoundError e) {
+ // We were able to load the adapter but its underlying
+ // logger library could not be found. This is normal and not
+ // a "flawed discovery", so just throw the error on
+ logDiagnostic("Unable to load logging library used by "
+ + logAdapterClass);
+ throw e;
+ } catch (Throwable t) {
+ // ExceptionInInitializerError
+ // NoSuchMethodException
+ // InvocationTargetException
+ // ClassCastException
+ // All mean the adapter and underlying logger library were found
+ // but there was a problem creating an instance.
+ // This is a "flawed discovery"
+
+ handleFlawedDiscovery(logAdapterClass, logClass, t);
+ // handleFlawedDiscovery should have thrown an LCE, but
+ // in case it didn't we'll throw one
+ throw new LogConfigurationException(t);
+ }
+
+ if (affectState) {
+ // We've succeeded, so set instance fields
+ this.logClassName = logClass.getName();
+ this.logConstructor = constructor;
+
+ // Identify the setLogFactory method (if there is one)
+ try {
+ this.logMethod = logClass.getMethod("setLogFactory",
+ logMethodSignature);
+ logDiagnostic("Found method setLogFactory(LogFactory) in "
+ + logClassName);
+ } catch (Throwable t) {
+ this.logMethod = null;
+ logDiagnostic(logAdapterClass + " does not declare method "
+ + "setLogFactory(LogFactory)");
+ }
+ }
+
+ return result;
+
+ }
+
+
+ /**
+ * Generates an internal diagnostic logging of the discovery failure and
+ * then throws a LogConfigurationException that wraps
+ * the passed Throwable.
+ *
+ * @param logClassName the class name of the Log implementation
+ * that could not be instantiated. Cannot be
+ * null.
+ * @param adapterClass Code whose name is
+ * logClassName, or null if
+ * discovery was unable to load the class.
+ * @param discoveryFlaw Throwable thrown during discovery.
+ *
+ * @throws LogConfigurationException ALWAYS
+ */
+ private void handleFlawedDiscovery(String logClassName,
+ Class adapterClass,
+ Throwable discoveryFlaw) {
+
+ // Output diagnostics
+
+ // For ClassCastException use the more complex diagnostic
+ // that analyzes the classloader hierarchy
+ if ( discoveryFlaw instanceof ClassCastException
+ && adapterClass != null) {
+ // reportInvalidAdapter returns a LogConfigurationException
+ // that wraps the ClassCastException; replace variable
+ // 'discoveryFlaw' with that so we can rethrow the LCE
+ discoveryFlaw = reportInvalidLogAdapter(adapterClass,
+ discoveryFlaw);
+ }
+ else {
+ logDiagnostic("Could not instantiate Log "
+ + logClassName + " -- "
+ + discoveryFlaw.getLocalizedMessage());
+ }
+
+
+ if (discoveryFlaw instanceof LogConfigurationException) {
+ throw (LogConfigurationException) discoveryFlaw;
+ }
+ else {
+ throw new LogConfigurationException(discoveryFlaw);
+ }
+
+ }
+
+
+ /**
+ * Report a problem loading the log adapter, then return
+ * a LogConfigurationException.
+ * + * There are two possible reasons why we successfully loaded the + * specified log adapter class then failed to cast it to a Log object: + *
+ * Here we try to figure out which case has occurred so we can give the
+ * user some reasonable feedback.
+ *
+ * @param logClass is the adapter class we successfully loaded (but which
+ * could not be cast to type logInterface). Cannot be null.
+ * @param cause is the Throwable to wrap.
+ *
+ * @return LogConfigurationException that wraps
+ * cause and includes a diagnostic message.
+ */
+ private LogConfigurationException reportInvalidLogAdapter(Class logClass,
+ Throwable cause) {
+
+ Class interfaces[] = logClass.getInterfaces();
+ for (int i = 0; i < interfaces.length; i++) {
+ if (LOG_INTERFACE.equals(interfaces[i].getName())) {
+
+ if (isDiagnosticsEnabled()) {
+
+ try {
+ // Need to load the log interface so we know its
+ // classloader for diagnostics
+ Class logInterface = null;
+ ClassLoader cl = getClassLoader(this.getClass());
+ if (cl == null) {
+ // we are probably in Java 1.1, but may also be
+ // running in some sort of embedded system..
+ logInterface = loadClass(LOG_INTERFACE);
+ } else {
+ // normal situation
+ logInterface = cl.loadClass(LOG_INTERFACE);
+ }
+
+ ClassLoader logInterfaceClassLoader = getClassLoader(logInterface);
+ ClassLoader logAdapterClassLoader = getClassLoader(logClass);
+ Class logAdapterInterface = interfaces[i];
+ ClassLoader logAdapterInterfaceClassLoader = getClassLoader(logAdapterInterface);
+ logDiagnostic(
+ "Class " + logClass.getName()
+ + " was found in classloader "
+ + objectId(logAdapterClassLoader)
+ + " but it implements the Log interface as loaded"
+ + " from classloader "
+ + objectId(logAdapterInterfaceClassLoader)
+ + " not the one loaded by this class's classloader "
+ + objectId(logInterfaceClassLoader));
+ } catch (Throwable t) {
+ ;
+ }
+ }
+
+ return new LogConfigurationException
+ ("Invalid class loader hierarchy. " +
+ "You have more than one version of '" +
+ LOG_INTERFACE + "' visible, which is " +
+ "not allowed.", cause);
+ }
+ }
+
+ return new LogConfigurationException
+ ("Class " + logClassName + " does not implement '" +
+ LOG_INTERFACE + "'.", cause);
+ }
}