Example usage for org.apache.commons.logging Log isDebugEnabled

List of usage examples for org.apache.commons.logging Log isDebugEnabled

Introduction

In this page you can find the example usage for org.apache.commons.logging Log isDebugEnabled.

Prototype

boolean isDebugEnabled();

Source Link

Document

Is debug logging currently enabled?

Usage

From source file:org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.java

/**
 * 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
 *//* w w w.j av  a2  s.c om*/
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 | Error ex) {
        logger.error("Context initialization failed", ex);
        servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, ex);
        throw ex;
    }
}

From source file:org.springframework.build.junit.Assume.java

/**
 * Assume that the specified log is not set to Trace or Debug.
 * @param log the log to test/*  ww w.  j  ava2 s.c  o  m*/
 */
public static void notLogging(Log log) {
    assumeFalse(log.isTraceEnabled());
    assumeFalse(log.isDebugEnabled());
}

From source file:org.springframework.cloud.config.server.environment.JGitEnvironmentRepositoryTests.java

@Test
public void shouldPrintStacktraceIfDebugEnabled() throws Exception {
    final Log mockLogger = mock(Log.class);
    JGitEnvironmentRepository envRepository = new JGitEnvironmentRepository(this.environment,
            new JGitEnvironmentProperties()) {
        @Override/* w w w . j  av a  2  s .c  o  m*/
        public void afterPropertiesSet() throws Exception {
            this.logger = mockLogger;
        }
    };
    envRepository.afterPropertiesSet();
    when(mockLogger.isDebugEnabled()).thenReturn(true);

    envRepository.warn("", new RuntimeException());

    verify(mockLogger).warn(eq(""));
    verify(mockLogger).debug(eq("Stacktrace for: "), any(RuntimeException.class));

    int numberOfInvocations = mockingDetails(mockLogger).getInvocations().size();
    assertThat(numberOfInvocations).as("should call isDebugEnabled warn and debug").isEqualTo(3);
}

From source file:org.springframework.cloud.stream.binder.rabbit.LocalizedQueueConnectionFactoryTests.java

@SuppressWarnings("unchecked")
@Test//w  w w.j  av a2s . c o m
public void testFailOver() throws Exception {
    ConnectionFactory defaultConnectionFactory = mockCF("localhost:1234");
    String rabbit1 = "localhost:1235";
    String rabbit2 = "localhost:1236";
    String[] addresses = new String[] { rabbit1, rabbit2 };
    String[] adminAddresses = new String[] { "http://localhost:11235", "http://localhost:11236" };
    String[] nodes = new String[] { "rabbit@foo", "rabbit@bar" };
    String vhost = "/";
    String username = "guest";
    String password = "guest";
    final AtomicBoolean firstServer = new AtomicBoolean(true);
    LocalizedQueueConnectionFactory lqcf = new LocalizedQueueConnectionFactory(defaultConnectionFactory,
            addresses, adminAddresses, nodes, vhost, username, password, false, null) {

        private final String[] nodes = new String[] { "rabbit@foo", "rabbit@bar" };

        @Override
        protected RestTemplate createRestTemplate(String adminUri) {
            return doCreateRestTemplate(adminUri, firstServer.get() ? nodes[0] : nodes[1]);
        }

        @Override
        protected ConnectionFactory createConnectionFactory(String address) throws Exception {
            return mockCF(address);
        }

    };
    Log logger = spy(TestUtils.getPropertyValue(lqcf, "logger", Log.class));
    new DirectFieldAccessor(lqcf).setPropertyValue("logger", logger);
    when(logger.isDebugEnabled()).thenReturn(true);
    ArgumentCaptor<String> captor = ArgumentCaptor.forClass(String.class);
    SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(lqcf);
    container.setQueueNames("q");
    container.afterPropertiesSet();
    container.start();
    Channel channel = this.channels.get(rabbit1);
    verify(channel).basicConsume(anyString(), anyBoolean(), anyString(), anyBoolean(), anyBoolean(), anyMap(),
            Matchers.any(Consumer.class));
    verify(logger, atLeast(1)).debug(captor.capture());
    assertTrue(assertLog(captor.getAllValues(), "Queue: q is on node: rabbit@foo at: localhost:1235"));

    // Fail rabbit1 and verify the container switches to rabbit2

    firstServer.set(false);
    when(channel.isOpen()).thenReturn(false);
    when(this.connections.get(rabbit1).isOpen()).thenReturn(false);
    this.consumers.get(rabbit1).handleCancel(consumerTags.get(rabbit1));
    assertTrue(latch.await(10, TimeUnit.SECONDS));
    channel = this.channels.get(rabbit2);
    verify(channel).basicConsume(anyString(), anyBoolean(), anyString(), anyBoolean(), anyBoolean(), anyMap(),
            Matchers.any(Consumer.class));
    container.stop();
    verify(logger, atLeast(1)).debug(captor.capture());
    assertTrue(assertLog(captor.getAllValues(), "Queue: q is on node: rabbit@bar at: localhost:1236"));
}

From source file:org.springframework.context.event.SimpleApplicationEventMulticaster.java

@SuppressWarnings({ "unchecked", "rawtypes" })
private void doInvokeListener(ApplicationListener listener, ApplicationEvent event) {
    try {//from   www  .  ja  v a2s. com
        listener.onApplicationEvent(event);
    } catch (ClassCastException ex) {
        String msg = ex.getMessage();
        if (msg == null || matchesClassCastMessage(msg, event.getClass().getName())) {
            // Possibly a lambda-defined listener which we could not resolve the generic event type for
            // -> let's suppress the exception and just log a debug message.
            Log logger = LogFactory.getLog(getClass());
            if (logger.isDebugEnabled()) {
                logger.debug("Non-matching event type for listener: " + listener, ex);
            }
        } else {
            throw ex;
        }
    }
}

From source file:org.springframework.core.annotation.AnnotationUtils.java

/**
 * 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./* www. jav a 2  s.  c om*/
 * <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(@Nullable 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 or (default) value lookup on an annotation type
        if (loggerToUse.isDebugEnabled()) {
            loggerToUse.debug("Failed to meta-introspect annotation [" + element + "]: " + ex);
        }
    } else {
        // Direct annotation lookup on regular Class, Method, Field
        if (loggerToUse.isInfoEnabled()) {
            loggerToUse.info("Failed to introspect annotations on [" + element + "]: " + ex);
        }
    }
}

From source file:org.springframework.core.log.LogFormatUtils.java

/**
 * Use this to log a message with different levels of detail (or different
 * messages) at TRACE vs DEBUG log levels. Effectively, a substitute for:
 * <pre class="code">/*from w  ww .jav a 2 s.  c  o  m*/
 * if (logger.isDebugEnabled()) {
 *   String str = logger.isTraceEnabled() ? "..." : "...";
 *   if (logger.isTraceEnabled()) {
 *     logger.trace(str);
 *   }
 *   else {
 *     logger.debug(str);
 *   }
 * }
 * </pre>
 * @param logger the logger to use to log the message
 * @param messageFactory function that accepts a boolean set to the value
 * of {@link Log#isTraceEnabled()}
 */
public static void traceDebug(Log logger, Function<Boolean, String> messageFactory) {
    if (logger.isDebugEnabled()) {
        boolean traceEnabled = logger.isTraceEnabled();
        String logMessage = messageFactory.apply(traceEnabled);
        if (traceEnabled) {
            logger.trace(logMessage);
        } else {
            logger.debug(logMessage);
        }
    }
}

From source file:org.springframework.data.gemfire.snapshot.SnapshotServiceFactoryBeanTest.java

@Test
public void logDebugWhenDebugging() {
    final Log mockLog = mock(Log.class, "MockLog");

    when(mockLog.isDebugEnabled()).thenReturn(true);

    TestSnapshotServiceAdapter snapshotService = new TestSnapshotServiceAdapter() {
        @Override/* w  w  w  .  ja  va  2s .c o m*/
        Log createLog() {
            return mockLog;
        }
    };

    Exception expectedException = new Exception("test");

    snapshotService.logDebug(expectedException, "Log message with argument (%1$s)", "test");

    verify(mockLog, times(1)).isDebugEnabled();
    verify(mockLog, times(1)).debug(eq("Log message with argument (test)"), eq(expectedException));
}

From source file:org.springframework.data.gemfire.snapshot.SnapshotServiceFactoryBeanTest.java

@Test
public void logDebugWhenNotDebugging() {
    final Log mockLog = mock(Log.class, "MockLog");

    when(mockLog.isDebugEnabled()).thenReturn(false);

    TestSnapshotServiceAdapter snapshotService = new TestSnapshotServiceAdapter() {
        @Override//from w w w.  j  a v  a2 s .c  o  m
        Log createLog() {
            return mockLog;
        }
    };

    snapshotService.logDebug(null, "Log message with argument (%1$s)", "test");

    verify(mockLog, times(1)).isDebugEnabled();
    verify(mockLog, never()).debug(any(String.class), any(Throwable.class));
}

From source file:org.springframework.extensions.surf.core.scripts.ScriptResourceHelper.java

/**
 * Recursively resolve imports in the specified scripts, adding the imports to the
 * specific list of scriplets to combine later.
 * //from   w  w w. j av  a  2  s. c om
 * @param location      Script location - used to ensure duplicates are not added
 * @param script        The script to recursively resolve imports for
 * @param scripts       The collection of scriplets to execute with imports resolved and removed
 */
private static void recurseScriptImports(String location, String script, ScriptResourceLoader loader,
        Map<String, String> scripts, Log logger) {
    int index = 0;
    // skip any initial whitespace
    for (; index < script.length(); index++) {
        if (Character.isWhitespace(script.charAt(index)) == false) {
            break;
        }
    }

    // Allow a comment marker to immediately precede the IMPORT_PREFIX to assist JS validation.
    if (script.startsWith(IMPORT_COMMENT_MARKER, index)) {
        index += IMPORT_COMMENT_MARKER.length();
    }

    // look for the "<import" directive marker
    if (script.startsWith(IMPORT_PREFIX, index)) {
        // skip whitespace between "<import" and "resource"
        boolean afterWhitespace = false;
        index += IMPORT_PREFIX.length() + 1;
        for (; index < script.length(); index++) {
            if (Character.isWhitespace(script.charAt(index)) == false) {
                afterWhitespace = true;
                break;
            }
        }
        if (afterWhitespace == true && script.startsWith(IMPORT_RESOURCE, index)) {
            // found an import line!
            index += IMPORT_RESOURCE.length();
            int resourceStart = index;
            for (; index < script.length(); index++) {
                if (script.charAt(index) == '"' && script.charAt(index + 1) == '>') {
                    // found end of import line - so we have a resource path
                    String resource = script.substring(resourceStart, index);

                    if (logger.isDebugEnabled())
                        logger.debug("Found script resource import: " + resource);

                    if (scripts.containsKey(resource) == false) {
                        // load the script resource (and parse any recursive includes...)
                        String includedScript = loader.loadScriptResource(resource);
                        if (includedScript != null) {
                            if (logger.isDebugEnabled())
                                logger.debug("Succesfully located script '" + resource + "'");
                            recurseScriptImports(resource, includedScript, loader, scripts, logger);
                        }
                    } else {
                        if (logger.isDebugEnabled())
                            logger.debug("Note: already imported resource: " + resource);
                    }

                    // continue scanning this script for additional includes
                    // skip the last two characters of the import directive
                    for (index += 2; index < script.length(); index++) {
                        if (Character.isWhitespace(script.charAt(index)) == false) {
                            break;
                        }
                    }
                    recurseScriptImports(location, script.substring(index), loader, scripts, logger);
                    return;
                }
            }
            // if we get here, we failed to find the end of an import line
            throw new ScriptException(
                    "Malformed 'import' line - must be first in file, no comments and strictly of the form:"
                            + "\r\n<import resource=\"...\">");
        } else {
            throw new ScriptException(
                    "Malformed 'import' line - must be first in file, no comments and strictly of the form:"
                            + "\r\n<import resource=\"...\">");
        }
    } else {
        // no (further) includes found - include the original script content
        if (logger.isDebugEnabled())
            logger.debug("Imports resolved, adding resource '" + location);
        if (logger.isTraceEnabled())
            logger.trace(script);
        scripts.put(location, script);
    }
}