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

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

Introduction

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

Prototype

boolean isInfoEnabled();

Source Link

Document

Is info logging currently enabled?

Usage

From source file:org.springframework.boot.StartupInfoLogger.java

public void logStarted(Log log, StopWatch stopWatch) {
    if (log.isInfoEnabled()) {
        log.info(getStartedMessage(stopWatch));
    }
}

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
 *//*from w w w . j  a  v  a2s. c  o  m*/
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.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.//  w  w w .jav a  2s . com
 * <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.flex.core.CommonsLoggingTarget.java

public void logEvent(LogEvent logevent) {
    String category = logevent.logger.getCategory();
    if (this.categoryPrefix != null) {
        category = this.categoryPrefix + "." + category;
    }//from   w  ww . java2 s.  c  o m
    Log log = LogFactory.getLog(category);
    switch (logevent.level) {
    case LogEvent.FATAL:
        if (log.isFatalEnabled()) {
            log.fatal(logevent.message, logevent.throwable);
        }
        break;
    case LogEvent.ERROR:
        if (log.isErrorEnabled()) {
            log.error(logevent.message, logevent.throwable);
        }
        break;
    case LogEvent.WARN:
        if (log.isWarnEnabled()) {
            log.warn(logevent.message, logevent.throwable);
        }
        break;
    case LogEvent.INFO:
        if (log.isInfoEnabled()) {
            log.info(logevent.message, logevent.throwable);
        }
        break;
    case LogEvent.DEBUG:
        if (log.isDebugEnabled()) {
            log.debug(logevent.message, logevent.throwable);
        }
        break;
    case LogEvent.ALL:
        if (log.isTraceEnabled()) {
            log.trace(logevent.message, logevent.throwable);
        }
        break;
    default:
        break;
    }
}

From source file:org.springframework.integration.channel.P2pChannelTests.java

/**
 * @param channel/*from   w w  w .  j  ava 2  s  .  com*/
 */
private void verifySubscriptions(final AbstractSubscribableChannel channel) {
    final Log logger = mock(Log.class);
    when(logger.isInfoEnabled()).thenReturn(true);
    final List<String> logs = new ArrayList<String>();
    doAnswer(new Answer<Object>() {
        public Object answer(InvocationOnMock invocation) throws Throwable {
            logs.add((String) invocation.getArguments()[0]);
            return null;
        }
    }).when(logger).info(Mockito.anyString());
    ReflectionUtils.doWithFields(AbstractMessageChannel.class, new FieldCallback() {
        public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {
            if ("logger".equals(field.getName())) {
                field.setAccessible(true);
                field.set(channel, logger);
            }
        }
    });
    String log = "Channel '" + channel.getComponentName() + "' has " + "%d subscriber(s).";

    MessageHandler handler1 = mock(MessageHandler.class);
    channel.subscribe(handler1);
    assertEquals(String.format(log, 1), logs.remove(0));
    MessageHandler handler2 = mock(MessageHandler.class);
    channel.subscribe(handler2);
    assertEquals(String.format(log, 2), logs.remove(0));
    channel.unsubscribe(handler1);
    assertEquals(String.format(log, 1), logs.remove(0));
    channel.unsubscribe(handler1);
    assertEquals(0, logs.size());
    channel.unsubscribe(handler2);
    assertEquals(String.format(log, 0), logs.remove(0));
    verify(logger, times(4)).info(Mockito.anyString());
}

From source file:org.springframework.integration.channel.P2pChannelTests.java

@Test
public void testExecutorChannelLoggingWithMoreThenOneSubscriber() {
    final ExecutorChannel channel = new ExecutorChannel(mock(Executor.class));
    channel.setBeanName("executorChannel");

    final Log logger = mock(Log.class);
    when(logger.isInfoEnabled()).thenReturn(true);
    ReflectionUtils.doWithFields(AbstractMessageChannel.class, new FieldCallback() {

        public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {
            if ("logger".equals(field.getName())) {
                field.setAccessible(true);
                field.set(channel, logger);
            }//from   w w w  . j  a  v a  2s  .  c  om
        }
    });
    channel.subscribe(mock(MessageHandler.class));
    channel.subscribe(mock(MessageHandler.class));
    verify(logger, times(2)).info(Mockito.anyString());
}

From source file:org.springframework.integration.channel.P2pChannelTests.java

@Test
public void testPubSubChannelLoggingWithMoreThenOneSubscriber() {
    final PublishSubscribeChannel channel = new PublishSubscribeChannel();
    channel.setBeanName("pubSubChannel");

    final Log logger = mock(Log.class);
    when(logger.isInfoEnabled()).thenReturn(true);
    ReflectionUtils.doWithFields(AbstractMessageChannel.class, new FieldCallback() {

        public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {
            if ("logger".equals(field.getName())) {
                field.setAccessible(true);
                field.set(channel, logger);
            }/*from  w  ww .  j  a  v  a  2s  .c o  m*/
        }
    });
    channel.subscribe(mock(MessageHandler.class));
    channel.subscribe(mock(MessageHandler.class));
    verify(logger, times(2)).info(Mockito.anyString());
}

From source file:org.springframework.integration.handler.LoggingHandlerTests.java

@Test
public void testDontEvaluateIfNotEnabled() {
    LoggingHandler loggingHandler = new LoggingHandler("INFO");
    DirectFieldAccessor accessor = new DirectFieldAccessor(loggingHandler);
    Log log = (Log) accessor.getPropertyValue("messageLogger");
    log = spy(log);/*from w w  w .  j  a  v a 2s  .c  o  m*/
    accessor.setPropertyValue("messageLogger", log);
    Expression expression = (Expression) accessor.getPropertyValue("expression");
    expression = spy(expression);
    accessor.setPropertyValue("expression", expression);
    when(log.isInfoEnabled()).thenReturn(false);
    loggingHandler.handleMessage(new GenericMessage<String>("foo"));
    verify(expression, never()).getValue(Mockito.any(EvaluationContext.class), Mockito.any());

    when(log.isInfoEnabled()).thenReturn(true);
    loggingHandler.handleMessage(new GenericMessage<String>("foo"));
    verify(expression, times(1)).getValue(Mockito.any(EvaluationContext.class), Mockito.any());
}

From source file:org.springframework.integration.handler.LoggingHandlerTests.java

@Test
public void testChangeLevel() {
    LoggingHandler loggingHandler = new LoggingHandler("INFO");
    DirectFieldAccessor accessor = new DirectFieldAccessor(loggingHandler);
    Log log = (Log) accessor.getPropertyValue("messageLogger");
    log = spy(log);/*w w  w  .j  av  a2 s. c o m*/
    accessor.setPropertyValue("messageLogger", log);
    when(log.isInfoEnabled()).thenReturn(true);
    loggingHandler.handleMessage(new GenericMessage<String>("foo"));
    verify(log, times(1)).info(Mockito.anyString());
    verify(log, never()).warn(Mockito.anyString());

    loggingHandler.setLevel(Level.WARN);
    loggingHandler.handleMessage(new GenericMessage<String>("foo"));
    verify(log, times(1)).info(Mockito.anyString());
    verify(log, times(1)).warn(Mockito.anyString());
}

From source file:org.springframework.integration.ip.tcp.connection.ConnectionFactoryTests.java

private void testEarlyClose(final AbstractServerConnectionFactory factory, String property, String message)
        throws Exception {
    factory.setApplicationEventPublisher(mock(ApplicationEventPublisher.class));
    factory.setBeanName("foo");
    factory.registerListener(mock(TcpListener.class));
    factory.afterPropertiesSet();/*  w ww. j a v a2 s  .c  o m*/
    Log logger = spy(TestUtils.getPropertyValue(factory, "logger", Log.class));
    new DirectFieldAccessor(factory).setPropertyValue("logger", logger);
    final CountDownLatch latch1 = new CountDownLatch(1);
    final CountDownLatch latch2 = new CountDownLatch(1);
    final CountDownLatch latch3 = new CountDownLatch(1);
    when(logger.isInfoEnabled()).thenReturn(true);
    when(logger.isDebugEnabled()).thenReturn(true);
    doAnswer(invocation -> {
        latch1.countDown();
        // wait until the stop nulls the channel
        latch2.await(10, TimeUnit.SECONDS);
        return null;
    }).when(logger).info(contains("Listening"));
    doAnswer(invocation -> {
        latch3.countDown();
        return null;
    }).when(logger).debug(contains(message));
    factory.start();
    assertTrue("missing info log", latch1.await(10, TimeUnit.SECONDS));
    // stop on a different thread because it waits for the executor
    Executors.newSingleThreadExecutor().execute(() -> factory.stop());
    int n = 0;
    DirectFieldAccessor accessor = new DirectFieldAccessor(factory);
    while (n++ < 200 && accessor.getPropertyValue(property) != null) {
        Thread.sleep(100);
    }
    assertTrue("Stop was not invoked in time", n < 200);
    latch2.countDown();
    assertTrue("missing debug log", latch3.await(10, TimeUnit.SECONDS));
    String expected = "foo, port=" + factory.getPort() + message;
    ArgumentCaptor<String> captor = ArgumentCaptor.forClass(String.class);
    verify(logger, atLeast(1)).debug(captor.capture());
    assertThat(captor.getAllValues(), hasItem(expected));
    factory.stop();
}