Search in sources :

Example 91 with Log

use of org.apache.commons.logging.Log in project spring-boot by spring-projects.

the class LoggingApplicationListenerTests method addLogPathProperty.

@Test
void addLogPathProperty() {
    addPropertiesToEnvironment(this.context, "logging.config=classpath:logback-nondefault.xml", "logging.file.path=" + this.tempDir);
    this.initializer.initialize(this.context.getEnvironment(), this.context.getClassLoader());
    Log logger = LogFactory.getLog(LoggingApplicationListenerTests.class);
    String existingOutput = this.output.toString();
    logger.info("Hello world");
    String output = this.output.toString().substring(existingOutput.length()).trim();
    assertThat(output).startsWith(new File(this.tempDir.toFile(), "spring.log").getAbsolutePath());
}
Also used : Log(org.apache.commons.logging.Log) LogFile(org.springframework.boot.logging.LogFile) File(java.io.File) Test(org.junit.jupiter.api.Test)

Example 92 with Log

use of org.apache.commons.logging.Log in project spring-boot by spring-projects.

the class SpringApplication method logStartupProfileInfo.

/**
 * Called to log active profile information.
 * @param context the application context
 */
protected void logStartupProfileInfo(ConfigurableApplicationContext context) {
    Log log = getApplicationLog();
    if (log.isInfoEnabled()) {
        List<String> activeProfiles = quoteProfiles(context.getEnvironment().getActiveProfiles());
        if (ObjectUtils.isEmpty(activeProfiles)) {
            List<String> defaultProfiles = quoteProfiles(context.getEnvironment().getDefaultProfiles());
            String message = String.format("%s default %s: ", defaultProfiles.size(), (defaultProfiles.size() <= 1) ? "profile" : "profiles");
            log.info("No active profile set, falling back to " + message + StringUtils.collectionToDelimitedString(defaultProfiles, ", "));
        } else {
            String message = (activeProfiles.size() == 1) ? "1 profile is active: " : activeProfiles.size() + " profiles are active: ";
            log.info("The following " + message + StringUtils.collectionToDelimitedString(activeProfiles, ", "));
        }
    }
}
Also used : Log(org.apache.commons.logging.Log)

Example 93 with Log

use of org.apache.commons.logging.Log in project platform_external_apache-http by android.

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 94 with Log

use of org.apache.commons.logging.Log in project platform_external_apache-http by android.

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 95 with Log

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

the class NavBlock method render.

@Override
public void render(Block html) {
    boolean addErrorsAndWarningsLink = false;
    Log log = LogFactory.getLog(NavBlock.class);
    if (log instanceof Log4JLogger) {
        Log4jWarningErrorMetricsAppender appender = Log4jWarningErrorMetricsAppender.findAppender();
        if (appender != null) {
            addErrorsAndWarningsLink = true;
        }
    }
    UL<DIV<Hamlet>> mainList = html.div("#nav").h3("Cluster").ul().li().a(url("cluster"), "About")._().li().a(url("nodes"), "Nodes")._().li().a(url("nodelabels"), "Node Labels")._();
    UL<LI<UL<DIV<Hamlet>>>> subAppsList = mainList.li().a(url("apps"), "Applications").ul();
    subAppsList.li()._();
    for (YarnApplicationState state : YarnApplicationState.values()) {
        subAppsList.li().a(url("apps", state.toString()), state.toString())._();
    }
    subAppsList._()._();
    UL<DIV<Hamlet>> tools = mainList.li().a(url("scheduler"), "Scheduler")._()._().h3("Tools").ul();
    tools.li().a("/conf", "Configuration")._().li().a("/logs", "Local logs")._().li().a("/stacks", "Server stacks")._().li().a("/jmx?qry=Hadoop:*", "Server metrics")._();
    if (addErrorsAndWarningsLink) {
        tools.li().a(url("errors-and-warnings"), "Errors/Warnings")._();
    }
    tools._()._();
}
Also used : DIV(org.apache.hadoop.yarn.webapp.hamlet.Hamlet.DIV) Log(org.apache.commons.logging.Log) Log4JLogger(org.apache.commons.logging.impl.Log4JLogger) Log4jWarningErrorMetricsAppender(org.apache.hadoop.yarn.util.Log4jWarningErrorMetricsAppender) YarnApplicationState(org.apache.hadoop.yarn.api.records.YarnApplicationState) LI(org.apache.hadoop.yarn.webapp.hamlet.Hamlet.LI)

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