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

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

Introduction

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

Prototype

boolean isTraceEnabled();

Source Link

Document

Is trace logging currently enabled?

Usage

From source file:org.springframework.aop.interceptor.AbstractTraceInterceptor.java

/**
 * Determine whether the given {@link Log} instance is enabled.
 * <p>Default is {@code true} when the "trace" level is enabled.
 * Subclasses can override this to change the level under which 'tracing' occurs.
 * @param logger the {@code Log} instance to check
 *///from   w  ww .  j  ava 2s . c om
protected boolean isLogEnabled(Log logger) {
    return logger.isTraceEnabled();
}

From source file:org.springframework.aop.interceptor.CustomizableTraceInterceptorTests.java

@Test
public void testSunnyDayPathLogsCorrectly() throws Throwable {

    MethodInvocation methodInvocation = mock(MethodInvocation.class);
    given(methodInvocation.getMethod()).willReturn(String.class.getMethod("toString", new Class[] {}));
    given(methodInvocation.getThis()).willReturn(this);

    Log log = mock(Log.class);
    given(log.isTraceEnabled()).willReturn(true);

    CustomizableTraceInterceptor interceptor = new StubCustomizableTraceInterceptor(log);
    interceptor.invoke(methodInvocation);

    verify(log, times(2)).trace(anyString());
}

From source file:org.springframework.aop.interceptor.CustomizableTraceInterceptorTests.java

@Test
public void testExceptionPathLogsCorrectly() throws Throwable {

    MethodInvocation methodInvocation = mock(MethodInvocation.class);

    IllegalArgumentException exception = new IllegalArgumentException();
    given(methodInvocation.getMethod()).willReturn(String.class.getMethod("toString", new Class[] {}));
    given(methodInvocation.getThis()).willReturn(this);
    given(methodInvocation.proceed()).willThrow(exception);

    Log log = mock(Log.class);
    given(log.isTraceEnabled()).willReturn(true);

    CustomizableTraceInterceptor interceptor = new StubCustomizableTraceInterceptor(log);
    try {//w ww. j a  v  a 2  s .  com
        interceptor.invoke(methodInvocation);
        fail("Must have propagated the IllegalArgumentException.");
    } catch (IllegalArgumentException expected) {
    }

    verify(log).trace(anyString());
    verify(log).trace(anyString(), eq(exception));
}

From source file:org.springframework.aop.interceptor.CustomizableTraceInterceptorTests.java

@Test
public void testSunnyDayPathLogsCorrectlyWithPrettyMuchAllPlaceholdersMatching() throws Throwable {

    MethodInvocation methodInvocation = mock(MethodInvocation.class);

    given(methodInvocation.getMethod()).willReturn(String.class.getMethod("toString", new Class[0]));
    given(methodInvocation.getThis()).willReturn(this);
    given(methodInvocation.getArguments()).willReturn(new Object[] { "$ One \\$", new Long(2) });
    given(methodInvocation.proceed()).willReturn("Hello!");

    Log log = mock(Log.class);
    given(log.isTraceEnabled()).willReturn(true);

    CustomizableTraceInterceptor interceptor = new StubCustomizableTraceInterceptor(log);
    interceptor.setEnterMessage(new StringBuffer().append("Entering the '")
            .append(CustomizableTraceInterceptor.PLACEHOLDER_METHOD_NAME).append("' method of the [")
            .append(CustomizableTraceInterceptor.PLACEHOLDER_TARGET_CLASS_NAME)
            .append("] class with the following args (")
            .append(CustomizableTraceInterceptor.PLACEHOLDER_ARGUMENTS).append(") and arg types (")
            .append(CustomizableTraceInterceptor.PLACEHOLDER_ARGUMENT_TYPES).append(").").toString());
    interceptor.setExitMessage(new StringBuffer().append("Exiting the '")
            .append(CustomizableTraceInterceptor.PLACEHOLDER_METHOD_NAME).append("' method of the [")
            .append(CustomizableTraceInterceptor.PLACEHOLDER_TARGET_CLASS_SHORT_NAME)
            .append("] class with the following args (")
            .append(CustomizableTraceInterceptor.PLACEHOLDER_ARGUMENTS).append(") and arg types (")
            .append(CustomizableTraceInterceptor.PLACEHOLDER_ARGUMENT_TYPES).append("), returning '")
            .append(CustomizableTraceInterceptor.PLACEHOLDER_RETURN_VALUE).append("' and taking '")
            .append(CustomizableTraceInterceptor.PLACEHOLDER_INVOCATION_TIME).append("' this long.")
            .toString());/*w  ww. j a  v  a2  s.c om*/
    interceptor.invoke(methodInvocation);

    verify(log, times(2)).trace(anyString());
}

From source file:org.springframework.aop.interceptor.DebugInterceptorTests.java

@Test
public void testSunnyDayPathLogsCorrectly() throws Throwable {

    MethodInvocation methodInvocation = mock(MethodInvocation.class);

    Log log = mock(Log.class);
    given(log.isTraceEnabled()).willReturn(true);

    DebugInterceptor interceptor = new StubDebugInterceptor(log);
    interceptor.invoke(methodInvocation);
    checkCallCountTotal(interceptor);// w w  w  . j av a 2s. co m

    verify(log, times(2)).trace(anyString());
}

From source file:org.springframework.aop.interceptor.DebugInterceptorTests.java

@Test
public void testExceptionPathStillLogsCorrectly() throws Throwable {

    MethodInvocation methodInvocation = mock(MethodInvocation.class);

    IllegalArgumentException exception = new IllegalArgumentException();
    given(methodInvocation.proceed()).willThrow(exception);

    Log log = mock(Log.class);
    given(log.isTraceEnabled()).willReturn(true);

    DebugInterceptor interceptor = new StubDebugInterceptor(log);
    try {//from   w ww.  ja  v a 2s.c  o m
        interceptor.invoke(methodInvocation);
        fail("Must have propagated the IllegalArgumentException.");
    } catch (IllegalArgumentException expected) {
    }
    checkCallCountTotal(interceptor);

    verify(log).trace(anyString());
    verify(log).trace(anyString(), eq(exception));
}

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//from w  w  w  .j a  v a2  s  .  co m
 */
public static void notLogging(Log log) {
    assumeFalse(log.isTraceEnabled());
    assumeFalse(log.isDebugEnabled());
}

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

@SuppressWarnings("unchecked")
@Test/*from  w ww.j a v  a  2  s.c  om*/
public void testBatchingAndCompression() throws Exception {
    RabbitTestBinder binder = getBinder();
    ExtendedProducerProperties<RabbitProducerProperties> producerProperties = createProducerProperties();
    producerProperties.getExtension().setDeliveryMode(MessageDeliveryMode.NON_PERSISTENT);
    producerProperties.getExtension().setBatchingEnabled(true);
    producerProperties.getExtension().setBatchSize(2);
    producerProperties.getExtension().setBatchBufferLimit(100000);
    producerProperties.getExtension().setBatchTimeout(30000);
    producerProperties.getExtension().setCompress(true);
    producerProperties.setRequiredGroups("default");

    DirectChannel output = createBindableChannel("input", createProducerBindingProperties(producerProperties));
    output.setBeanName("batchingProducer");
    Binding<MessageChannel> producerBinding = binder.bindProducer("batching.0", output, producerProperties);

    Log logger = spy(TestUtils.getPropertyValue(binder, "binder.compressingPostProcessor.logger", Log.class));
    new DirectFieldAccessor(TestUtils.getPropertyValue(binder, "binder.compressingPostProcessor"))
            .setPropertyValue("logger", logger);
    when(logger.isTraceEnabled()).thenReturn(true);

    assertThat(TestUtils.getPropertyValue(binder, "binder.compressingPostProcessor.level"))
            .isEqualTo(Deflater.BEST_SPEED);

    output.send(new GenericMessage<>("foo".getBytes()));
    output.send(new GenericMessage<>("bar".getBytes()));

    Object out = spyOn("batching.0.default").receive(false);
    assertThat(out).isInstanceOf(byte[].class);
    assertThat(new String((byte[]) out)).isEqualTo("\u0000\u0000\u0000\u0003foo\u0000\u0000\u0000\u0003bar");

    ArgumentCaptor<Object> captor = ArgumentCaptor.forClass(Object.class);
    verify(logger).trace(captor.capture());
    assertThat(captor.getValue().toString()).contains(("Compressed 14 to "));

    QueueChannel input = new QueueChannel();
    input.setBeanName("batchingConsumer");
    Binding<MessageChannel> consumerBinding = binder.bindConsumer("batching.0", "test", input,
            createConsumerProperties());

    output.send(new GenericMessage<>("foo".getBytes()));
    output.send(new GenericMessage<>("bar".getBytes()));

    Message<byte[]> in = (Message<byte[]>) input.receive(10000);
    assertThat(in).isNotNull();
    assertThat(new String(in.getPayload())).isEqualTo("foo");
    in = (Message<byte[]>) input.receive(10000);
    assertThat(in).isNotNull();
    assertThat(new String(in.getPayload())).isEqualTo("bar");
    assertThat(in.getHeaders().get(AmqpHeaders.DELIVERY_MODE)).isNull();

    producerBinding.unbind();
    consumerBinding.unbind();
}

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">//  ww  w. ja  v 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.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.
 * // w  w w .j  a v a 2s. co  m
 * @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);
    }
}