Search in sources :

Example 96 with Log

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

the class ContextLoader method initWebApplicationContext.

/**
	 * Initialize Spring's web application context for the given servlet context,
	 * using the application context provided at construction time, or creating a new one
	 * according to the "{@link #CONTEXT_CLASS_PARAM contextClass}" and
	 * "{@link #CONFIG_LOCATION_PARAM contextConfigLocation}" context-params.
	 * @param servletContext current servlet context
	 * @return the new WebApplicationContext
	 * @see #ContextLoader(WebApplicationContext)
	 * @see #CONTEXT_CLASS_PARAM
	 * @see #CONFIG_LOCATION_PARAM
	 */
public WebApplicationContext initWebApplicationContext(ServletContext servletContext) {
    if (servletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE) != null) {
        throw new IllegalStateException("Cannot initialize context because there is already a root application context present - " + "check whether you have multiple ContextLoader* definitions in your web.xml!");
    }
    Log logger = LogFactory.getLog(ContextLoader.class);
    servletContext.log("Initializing Spring root WebApplicationContext");
    if (logger.isInfoEnabled()) {
        logger.info("Root WebApplicationContext: initialization started");
    }
    long startTime = System.currentTimeMillis();
    try {
        // it is available on ServletContext shutdown.
        if (this.context == null) {
            this.context = createWebApplicationContext(servletContext);
        }
        if (this.context instanceof ConfigurableWebApplicationContext) {
            ConfigurableWebApplicationContext cwac = (ConfigurableWebApplicationContext) this.context;
            if (!cwac.isActive()) {
                // setting the parent context, setting the application context id, etc
                if (cwac.getParent() == null) {
                    // The context instance was injected without an explicit parent ->
                    // determine parent for root web application context, if any.
                    ApplicationContext parent = loadParentContext(servletContext);
                    cwac.setParent(parent);
                }
                configureAndRefreshWebApplicationContext(cwac, servletContext);
            }
        }
        servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.context);
        ClassLoader ccl = Thread.currentThread().getContextClassLoader();
        if (ccl == ContextLoader.class.getClassLoader()) {
            currentContext = this.context;
        } else if (ccl != null) {
            currentContextPerThread.put(ccl, this.context);
        }
        if (logger.isDebugEnabled()) {
            logger.debug("Published root WebApplicationContext as ServletContext attribute with name [" + WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE + "]");
        }
        if (logger.isInfoEnabled()) {
            long elapsedTime = System.currentTimeMillis() - startTime;
            logger.info("Root WebApplicationContext: initialization completed in " + elapsedTime + " ms");
        }
        return this.context;
    } catch (RuntimeException ex) {
        logger.error("Context initialization failed", ex);
        servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, ex);
        throw ex;
    } catch (Error err) {
        logger.error("Context initialization failed", err);
        servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, err);
        throw err;
    }
}
Also used : ApplicationContext(org.springframework.context.ApplicationContext) ConfigurableApplicationContext(org.springframework.context.ConfigurableApplicationContext) Log(org.apache.commons.logging.Log)

Example 97 with Log

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

the class ErrorsAndWarningsBlock method render.

@Override
protected void render(Block html) {
    Log log = LogFactory.getLog(ErrorsAndWarningsBlock.class);
    boolean isAdmin = false;
    UserGroupInformation callerUGI = this.getCallerUGI();
    if (adminAclsManager.areACLsEnabled()) {
        if (callerUGI != null && adminAclsManager.isAdmin(callerUGI)) {
            isAdmin = true;
        }
    } else {
        isAdmin = true;
    }
    if (!isAdmin) {
        html.div().p()._("This page is for admins only.")._()._();
        return;
    }
    if (log instanceof Log4JLogger) {
        html._(ErrorMetrics.class);
        html._(WarningMetrics.class);
        html.div().button().$onclick("reloadPage()").b("View data for the last ")._().select().$id("cutoff").option().$value("60")._("1 min")._().option().$value("300")._("5 min")._().option().$value("900")._("15 min")._().option().$value("3600")._("1 hour")._().option().$value("21600")._("6 hours")._().option().$value("43200")._("12 hours")._().option().$value("86400")._("24 hours")._()._()._();
        String script = "function reloadPage() {" + " var timePeriod = $(\"#cutoff\").val();" + " document.location.href = '/cluster/errors-and-warnings?cutoff=' + timePeriod" + "}";
        script = script + "; function toggleContent(element) {" + "  $(element).parent().siblings('.toggle-content').fadeToggle();" + "}";
        html.script().$type("text/javascript")._(script)._();
        html.style(".toggle-content { display: none; }");
        Log4jWarningErrorMetricsAppender appender = Log4jWarningErrorMetricsAppender.findAppender();
        if (appender == null) {
            return;
        }
        List<Long> cutoff = new ArrayList<>();
        Hamlet.TBODY<Hamlet.TABLE<Hamlet>> errorsTable = html.table("#messages").thead().tr().th(".message", "Message").th(".type", "Type").th(".count", "Count").th(".lasttime", "Latest Message Time")._()._().tbody();
        // cutoff has to be in seconds
        cutoff.add((Time.now() - cutoffPeriodSeconds * 1000) / 1000);
        List<Map<String, Log4jWarningErrorMetricsAppender.Element>> errorsData = appender.getErrorMessagesAndCounts(cutoff);
        List<Map<String, Log4jWarningErrorMetricsAppender.Element>> warningsData = appender.getWarningMessagesAndCounts(cutoff);
        Map<String, List<Map<String, Log4jWarningErrorMetricsAppender.Element>>> sources = new HashMap<>();
        sources.put("Error", errorsData);
        sources.put("Warning", warningsData);
        int maxDisplayLength = 80;
        for (Map.Entry<String, List<Map<String, Log4jWarningErrorMetricsAppender.Element>>> source : sources.entrySet()) {
            String type = source.getKey();
            List<Map<String, Log4jWarningErrorMetricsAppender.Element>> data = source.getValue();
            if (data.size() > 0) {
                Map<String, Log4jWarningErrorMetricsAppender.Element> map = data.get(0);
                for (Map.Entry<String, Log4jWarningErrorMetricsAppender.Element> entry : map.entrySet()) {
                    String message = entry.getKey();
                    Hamlet.TR<Hamlet.TBODY<Hamlet.TABLE<Hamlet>>> row = errorsTable.tr();
                    Hamlet.TD<Hamlet.TR<Hamlet.TBODY<Hamlet.TABLE<Hamlet>>>> cell = row.td();
                    if (message.length() > maxDisplayLength || message.contains("\n")) {
                        String displayMessage = entry.getKey().split("\n")[0];
                        if (displayMessage.length() > maxDisplayLength) {
                            displayMessage = displayMessage.substring(0, maxDisplayLength);
                        }
                        cell.pre().a().$href("#").$onclick("toggleContent(this);").$style("white-space: pre")._(displayMessage)._()._().div().$class("toggle-content").pre()._(message)._()._()._();
                    } else {
                        cell.pre()._(message)._()._();
                    }
                    Log4jWarningErrorMetricsAppender.Element ele = entry.getValue();
                    row.td(type).td(String.valueOf(ele.count)).td(Times.format(ele.timestampSeconds * 1000))._();
                }
            }
        }
        errorsTable._()._();
    }
}
Also used : Hamlet(org.apache.hadoop.yarn.webapp.hamlet.Hamlet) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) ArrayList(java.util.ArrayList) List(java.util.List) UserGroupInformation(org.apache.hadoop.security.UserGroupInformation) Log(org.apache.commons.logging.Log) Log4JLogger(org.apache.commons.logging.impl.Log4JLogger) Log4jWarningErrorMetricsAppender(org.apache.hadoop.yarn.util.Log4jWarningErrorMetricsAppender) HashMap(java.util.HashMap) Map(java.util.Map)

Example 98 with Log

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

the class ServletWebServerApplicationContext method prepareWebApplicationContext.

/**
	 * Prepare the {@link WebApplicationContext} with the given fully loaded
	 * {@link ServletContext}. This method is usually called from
	 * {@link ServletContextInitializer#onStartup(ServletContext)} and is similar to the
	 * functionality usually provided by a {@link ContextLoaderListener}.
	 * @param servletContext the operational servlet context
	 */
protected void prepareWebApplicationContext(ServletContext servletContext) {
    Object rootContext = servletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
    if (rootContext != null) {
        if (rootContext == this) {
            throw new IllegalStateException("Cannot initialize context because there is already a root application context present - " + "check whether you have multiple ServletContextInitializers!");
        }
        return;
    }
    Log logger = LogFactory.getLog(ContextLoader.class);
    servletContext.log("Initializing Spring embedded WebApplicationContext");
    try {
        servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this);
        if (logger.isDebugEnabled()) {
            logger.debug("Published root WebApplicationContext as ServletContext attribute with name [" + WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE + "]");
        }
        setServletContext(servletContext);
        if (logger.isInfoEnabled()) {
            long elapsedTime = System.currentTimeMillis() - getStartupDate();
            logger.info("Root WebApplicationContext: initialization completed in " + elapsedTime + " ms");
        }
    } catch (RuntimeException ex) {
        logger.error("Context initialization failed", ex);
        servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, ex);
        throw ex;
    } catch (Error ex) {
        logger.error("Context initialization failed", ex);
        servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, ex);
        throw ex;
    }
}
Also used : Log(org.apache.commons.logging.Log)

Example 99 with Log

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

the class AnnotationUtils method handleIntrospectionFailure.

/**
	 * Handle the supplied annotation introspection exception.
	 * <p>If the supplied exception is an {@link AnnotationConfigurationException},
	 * it will simply be thrown, allowing it to propagate to the caller, and
	 * nothing will be logged.
	 * <p>Otherwise, this method logs an introspection failure (in particular
	 * {@code TypeNotPresentExceptions}) before moving on, assuming nested
	 * Class values were not resolvable within annotation attributes and
	 * thereby effectively pretending there were no annotations on the specified
	 * element.
	 * @param element the element that we tried to introspect annotations on
	 * @param ex the exception that we encountered
	 * @see #rethrowAnnotationConfigurationException
	 */
static void handleIntrospectionFailure(AnnotatedElement element, Throwable ex) {
    rethrowAnnotationConfigurationException(ex);
    Log loggerToUse = logger;
    if (loggerToUse == null) {
        loggerToUse = LogFactory.getLog(AnnotationUtils.class);
        logger = loggerToUse;
    }
    if (element instanceof Class && Annotation.class.isAssignableFrom((Class<?>) element)) {
        // Meta-annotation lookup on an annotation type
        if (loggerToUse.isDebugEnabled()) {
            loggerToUse.debug("Failed to introspect meta-annotations on [" + element + "]: " + ex);
        }
    } else {
        // Direct annotation lookup on regular Class, Method, Field
        if (loggerToUse.isInfoEnabled()) {
            loggerToUse.info("Failed to introspect annotations on [" + element + "]: " + ex);
        }
    }
}
Also used : Log(org.apache.commons.logging.Log) Annotation(java.lang.annotation.Annotation)

Example 100 with Log

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

the class HttpSessionEventPublisher method sessionCreated.

/**
	 * Handles the HttpSessionEvent by publishing a {@link HttpSessionCreatedEvent} to the
	 * application appContext.
	 *
	 * @param event HttpSessionEvent passed in by the container
	 */
public void sessionCreated(HttpSessionEvent event) {
    HttpSessionCreatedEvent e = new HttpSessionCreatedEvent(event.getSession());
    Log log = LogFactory.getLog(LOGGER_NAME);
    if (log.isDebugEnabled()) {
        log.debug("Publishing event: " + e);
    }
    getContext(event.getSession().getServletContext()).publishEvent(e);
}
Also used : Log(org.apache.commons.logging.Log)

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