Search in sources :

Example 11 with Log

use of org.apache.commons.logging.Log in project XobotOS by xamarin.

the class LogFactoryImpl method getInstance.

/**
     * <p>Construct (if necessary) and return a <code>Log</code> instance,
     * using the factory's current set of configuration attributes.</p>
     *
     * <p><strong>NOTE</strong> - Depending upon the implementation of
     * the <code>LogFactory</code> you are using, the <code>Log</code>
     * instance you are returned may or may not be local to the current
     * application, and may or may not be returned again on a subsequent
     * call with the same name argument.</p>
     *
     * @param name Logical name of the <code>Log</code> instance to be
     *  returned (the meaning of this name is only known to the underlying
     *  logging implementation that is being wrapped)
     *
     * @exception LogConfigurationException if a suitable <code>Log</code>
     *  instance cannot be returned
     */
public Log getInstance(String name) throws LogConfigurationException {
    Log instance = (Log) instances.get(name);
    if (instance == null) {
        instance = newInstance(name);
        instances.put(name, instance);
    }
    return (instance);
}
Also used : Log(org.apache.commons.logging.Log)

Example 12 with Log

use of org.apache.commons.logging.Log in project XobotOS by xamarin.

the class LogFactoryImpl method createLogFromClass.

/**
     * 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 {
            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");
                }
                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);
            // 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) {
            // 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) {
            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;
}
Also used : Log(org.apache.commons.logging.Log) Constructor(java.lang.reflect.Constructor) URL(java.net.URL) LogConfigurationException(org.apache.commons.logging.LogConfigurationException)

Example 13 with Log

use of org.apache.commons.logging.Log in project XobotOS by xamarin.

the class LogFactoryImpl method newInstance.

/**
     * 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) {
        // 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) {
        // previously discovered
        throw new LogConfigurationException(t);
    }
}
Also used : Log(org.apache.commons.logging.Log) LogConfigurationException(org.apache.commons.logging.LogConfigurationException) InvocationTargetException(java.lang.reflect.InvocationTargetException)

Example 14 with Log

use of org.apache.commons.logging.Log in project hadoop by apache.

the class HttpRequestLog method getRequestLog.

public static RequestLog getRequestLog(String name) {
    String lookup = serverToComponent.get(name);
    if (lookup != null) {
        name = lookup;
    }
    String loggerName = "http.requests." + name;
    String appenderName = name + "requestlog";
    Log logger = LogFactory.getLog(loggerName);
    boolean isLog4JLogger;
    ;
    try {
        isLog4JLogger = logger instanceof Log4JLogger;
    } catch (NoClassDefFoundError err) {
        // In some dependent projects, log4j may not even be on the classpath at
        // runtime, in which case the above instanceof check will throw
        // NoClassDefFoundError.
        LOG.debug("Could not load Log4JLogger class", err);
        isLog4JLogger = false;
    }
    if (isLog4JLogger) {
        Log4JLogger httpLog4JLog = (Log4JLogger) logger;
        Logger httpLogger = httpLog4JLog.getLogger();
        Appender appender = null;
        try {
            appender = httpLogger.getAppender(appenderName);
        } catch (LogConfigurationException e) {
            LOG.warn("Http request log for " + loggerName + " could not be created");
            throw e;
        }
        if (appender == null) {
            LOG.info("Http request log for " + loggerName + " is not defined");
            return null;
        }
        if (appender instanceof HttpRequestLogAppender) {
            HttpRequestLogAppender requestLogAppender = (HttpRequestLogAppender) appender;
            NCSARequestLog requestLog = new NCSARequestLog();
            requestLog.setFilename(requestLogAppender.getFilename());
            requestLog.setRetainDays(requestLogAppender.getRetainDays());
            return requestLog;
        } else {
            LOG.warn("Jetty request log for " + loggerName + " was of the wrong class");
            return null;
        }
    } else {
        LOG.warn("Jetty request log can only be enabled using Log4j");
        return null;
    }
}
Also used : Appender(org.apache.log4j.Appender) NCSARequestLog(org.eclipse.jetty.server.NCSARequestLog) RequestLog(org.eclipse.jetty.server.RequestLog) Log(org.apache.commons.logging.Log) Log4JLogger(org.apache.commons.logging.impl.Log4JLogger) NCSARequestLog(org.eclipse.jetty.server.NCSARequestLog) LogConfigurationException(org.apache.commons.logging.LogConfigurationException) Logger(org.apache.log4j.Logger) Log4JLogger(org.apache.commons.logging.impl.Log4JLogger)

Example 15 with Log

use of org.apache.commons.logging.Log in project hadoop by apache.

the class TestServer method testLogExceptions.

@Test(timeout = 300000)
public void testLogExceptions() throws Exception {
    final Configuration conf = new Configuration();
    final Call dummyCall = new Call(0, 0, null, null);
    Log logger = mock(Log.class);
    Server server = new Server("0.0.0.0", 0, LongWritable.class, 1, conf) {

        @Override
        public Writable call(RPC.RpcKind rpcKind, String protocol, Writable param, long receiveTime) throws Exception {
            return null;
        }
    };
    server.addSuppressedLoggingExceptions(TestException1.class);
    server.addTerseExceptions(TestException2.class);
    // Nothing should be logged for a suppressed exception.
    server.logException(logger, new TestException1(), dummyCall);
    verifyZeroInteractions(logger);
    // No stack trace should be logged for a terse exception.
    server.logException(logger, new TestException2(), dummyCall);
    verify(logger, times(1)).info(anyObject());
    // Full stack trace should be logged for other exceptions.
    final Throwable te3 = new TestException3();
    server.logException(logger, te3, dummyCall);
    verify(logger, times(1)).info(anyObject(), eq(te3));
}
Also used : Call(org.apache.hadoop.ipc.Server.Call) Configuration(org.apache.hadoop.conf.Configuration) Log(org.apache.commons.logging.Log) Writable(org.apache.hadoop.io.Writable) LongWritable(org.apache.hadoop.io.LongWritable) Test(org.junit.Test)

Aggregations

Log (org.apache.commons.logging.Log)188 Test (org.junit.Test)51 Test (org.junit.jupiter.api.Test)40 DirectFieldAccessor (org.springframework.beans.DirectFieldAccessor)35 ArgumentMatchers.anyString (org.mockito.ArgumentMatchers.anyString)19 BeanFactory (org.springframework.beans.factory.BeanFactory)17 CountDownLatch (java.util.concurrent.CountDownLatch)15 LogConfigurationException (org.apache.commons.logging.LogConfigurationException)15 ArrayList (java.util.ArrayList)12 File (java.io.File)11 QueueChannel (org.springframework.integration.channel.QueueChannel)11 MethodInvocation (org.aopalliance.intercept.MethodInvocation)10 IOException (java.io.IOException)9 AtomicReference (java.util.concurrent.atomic.AtomicReference)9 Log4JLogger (org.apache.commons.logging.impl.Log4JLogger)9 Message (org.springframework.messaging.Message)8 List (java.util.List)7 ApplicationEventPublisher (org.springframework.context.ApplicationEventPublisher)7 InputStream (java.io.InputStream)6 LogFactory (org.apache.commons.logging.LogFactory)6