Search in sources :

Example 36 with ListAppender

use of org.apache.logging.log4j.core.test.appender.ListAppender in project logging-log4j2 by apache.

the class GelfLayoutTest method testCompressedLayout.

private void testCompressedLayout(final CompressionType compressionType, final boolean includeStacktrace, final boolean includeThreadContext, String host, final boolean includeNullDelimiter, final boolean includeNewLineDelimiter) throws IOException {
    for (final Appender appender : root.getAppenders().values()) {
        root.removeAppender(appender);
    }
    // set up appenders
    final GelfLayout layout = GelfLayout.newBuilder().setConfiguration(ctx.getConfiguration()).setHost(host).setAdditionalFields(new KeyValuePair[] { new KeyValuePair(KEY1, VALUE1), new KeyValuePair(KEY2, "${java:runtime}") }).setCompressionType(compressionType).setCompressionThreshold(1024).setIncludeStacktrace(includeStacktrace).setIncludeThreadContext(includeThreadContext).setIncludeNullDelimiter(includeNullDelimiter).setIncludeNewLineDelimiter(includeNewLineDelimiter).build();
    final ListAppender eventAppender = new ListAppender("Events", null, null, true, false);
    final ListAppender rawAppender = new ListAppender("Raw", null, layout, true, true);
    final ListAppender formattedAppender = new ListAppender("Formatted", null, layout, true, false);
    final EncodingListAppender encodedAppender = new EncodingListAppender("Encoded", null, layout, false, true);
    eventAppender.start();
    rawAppender.start();
    formattedAppender.start();
    encodedAppender.start();
    if (host == null) {
        host = NetUtils.getLocalHostname();
    }
    final JavaLookup javaLookup = new JavaLookup();
    // set appenders on root and set level to debug
    root.addAppender(eventAppender);
    root.addAppender(rawAppender);
    root.addAppender(formattedAppender);
    root.addAppender(encodedAppender);
    root.setLevel(Level.DEBUG);
    root.debug(LINE1);
    ThreadContext.put(MDCKEY1, MDCVALUE1);
    ThreadContext.put(MDCKEY2, MDCVALUE2);
    root.info(LINE2);
    final Exception exception = new RuntimeException("some error");
    root.error(LINE3, exception);
    formattedAppender.stop();
    final List<LogEvent> events = eventAppender.getEvents();
    final List<byte[]> raw = rawAppender.getData();
    final List<String> messages = formattedAppender.getMessages();
    final List<byte[]> raw2 = encodedAppender.getData();
    final String threadName = Thread.currentThread().getName();
    // @formatter:off
    assertJsonEquals("{" + "\"version\": \"1.1\"," + "\"host\": \"" + host + "\"," + "\"timestamp\": " + GelfLayout.formatTimestamp(events.get(0).getTimeMillis()) + "," + "\"level\": 7," + "\"_thread\": \"" + threadName + "\"," + "\"_logger\": \"\"," + "\"short_message\": \"" + LINE1 + "\"," + "\"_" + KEY1 + "\": \"" + VALUE1 + "\"," + "\"_" + KEY2 + "\": \"" + javaLookup.getRuntime() + "\"" + "}", messages.get(0));
    assertJsonEquals("{" + "\"version\": \"1.1\"," + "\"host\": \"" + host + "\"," + "\"timestamp\": " + GelfLayout.formatTimestamp(events.get(1).getTimeMillis()) + "," + "\"level\": 6," + "\"_thread\": \"" + threadName + "\"," + "\"_logger\": \"\"," + "\"short_message\": \"" + LINE2 + "\"," + (includeThreadContext ? "\"_" + MDCKEY1 + "\": \"" + MDCVALUE1 + "\"," + "\"_" + MDCKEY2 + "\": \"" + MDCVALUE2 + "\"," : "") + "\"_" + KEY1 + "\": \"" + VALUE1 + "\"," + "\"_" + KEY2 + "\": \"" + javaLookup.getRuntime() + "\"" + "}", messages.get(1));
    // @formatter:on
    final byte[] compressed = raw.get(2);
    final byte[] compressed2 = raw2.get(2);
    final ByteArrayInputStream bais = new ByteArrayInputStream(compressed);
    final ByteArrayInputStream bais2 = new ByteArrayInputStream(compressed2);
    InputStream inflaterStream;
    InputStream inflaterStream2;
    switch(compressionType) {
        case GZIP:
            inflaterStream = new GZIPInputStream(bais);
            inflaterStream2 = new GZIPInputStream(bais2);
            break;
        case ZLIB:
            inflaterStream = new InflaterInputStream(bais);
            inflaterStream2 = new InflaterInputStream(bais2);
            break;
        case OFF:
            inflaterStream = bais;
            inflaterStream2 = bais2;
            break;
        default:
            throw new IllegalStateException("Missing test case clause");
    }
    final byte[] uncompressed = IOUtils.toByteArray(inflaterStream);
    final byte[] uncompressed2 = IOUtils.toByteArray(inflaterStream2);
    inflaterStream.close();
    inflaterStream2.close();
    final String uncompressedString = new String(uncompressed, layout.getCharset());
    final String uncompressedString2 = new String(uncompressed2, layout.getCharset());
    // @formatter:off
    final String expected = "{" + "\"version\": \"1.1\"," + "\"host\": \"" + host + "\"," + "\"timestamp\": " + GelfLayout.formatTimestamp(events.get(2).getTimeMillis()) + "," + "\"level\": 3," + "\"_thread\": \"" + threadName + "\"," + "\"_logger\": \"\"," + "\"short_message\": \"" + LINE3 + "\"," + "\"full_message\": \"" + String.valueOf(JsonStringEncoder.getInstance().quoteAsString(includeStacktrace ? GelfLayout.formatThrowable(exception).toString() : exception.toString())) + "\"," + (includeThreadContext ? "\"_" + MDCKEY1 + "\": \"" + MDCVALUE1 + "\"," + "\"_" + MDCKEY2 + "\": \"" + MDCVALUE2 + "\"," : "") + "\"_" + KEY1 + "\": \"" + VALUE1 + "\"," + "\"_" + KEY2 + "\": \"" + javaLookup.getRuntime() + "\"" + "}";
    // @formatter:on
    assertJsonEquals(expected, uncompressedString);
    assertJsonEquals(expected, uncompressedString2);
    if (includeNullDelimiter) {
        assertEquals(uncompressedString.indexOf('\0'), uncompressedString.length() - 1);
        assertEquals(uncompressedString2.indexOf('\0'), uncompressedString2.length() - 1);
    }
    if (includeNewLineDelimiter) {
        assertEquals(uncompressedString.indexOf('\n'), uncompressedString.length() - 1);
        assertEquals(uncompressedString2.indexOf('\n'), uncompressedString2.length() - 1);
    }
}
Also used : ListAppender(org.apache.logging.log4j.core.test.appender.ListAppender) EncodingListAppender(org.apache.logging.log4j.core.test.appender.EncodingListAppender) KeyValuePair(org.apache.logging.log4j.core.util.KeyValuePair) GZIPInputStream(java.util.zip.GZIPInputStream) InflaterInputStream(java.util.zip.InflaterInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) InflaterInputStream(java.util.zip.InflaterInputStream) JavaLookup(org.apache.logging.log4j.core.lookup.JavaLookup) EncodingListAppender(org.apache.logging.log4j.core.test.appender.EncodingListAppender) IOException(java.io.IOException) GZIPInputStream(java.util.zip.GZIPInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) ListAppender(org.apache.logging.log4j.core.test.appender.ListAppender) EncodingListAppender(org.apache.logging.log4j.core.test.appender.EncodingListAppender)

Example 37 with ListAppender

use of org.apache.logging.log4j.core.test.appender.ListAppender in project logging-log4j2 by apache.

the class Rfc5424LayoutTest method testCollection.

/**
 * Test case for MDC conversion pattern.
 */
@Test
public void testCollection() throws Exception {
    for (final Appender appender : root.getAppenders().values()) {
        root.removeAppender(appender);
    }
    // set up appender
    final AbstractStringLayout layout = Rfc5424Layout.createLayout(Facility.LOCAL0, "Event", 3692, true, "RequestContext", null, null, true, null, "ATM", null, "key1, key2, locale", null, "loginId", null, true, null, null);
    final ListAppender appender = new ListAppender("List", null, layout, true, false);
    appender.start();
    // set appender on root and set level to debug
    root.addAppender(appender);
    root.setLevel(Level.DEBUG);
    ThreadContext.put("loginId", "JohnDoe");
    ThreadContext.put("ipAddress", "192.168.0.120");
    ThreadContext.put("locale", Locale.US.getDisplayName());
    try {
        final StructuredDataMessage msg = new StructuredDataMessage("Transfer@18060", "Transfer Complete", "Audit");
        msg.put("ToAccount", "123456");
        msg.put("FromAccount", "123457");
        msg.put("Amount", "200.00");
        final StructuredDataMessage msg2 = new StructuredDataMessage("Extra@18060", null, "Audit");
        msg2.put("Item1", "Hello");
        msg2.put("Item2", "World");
        List<StructuredDataMessage> messages = new ArrayList<>();
        messages.add(msg);
        messages.add(msg2);
        final StructuredDataCollectionMessage collectionMessage = new StructuredDataCollectionMessage(messages);
        root.info(MarkerManager.getMarker("EVENT"), collectionMessage);
        List<String> list = appender.getMessages();
        String result = list.get(0);
        assertTrue(result.contains(collectionLine1), "Expected line to contain " + collectionLine1 + ", Actual " + result);
        assertTrue(result.contains(collectionLine2), "Expected line to contain " + collectionLine2 + ", Actual " + result);
        assertTrue(result.contains(collectionLine3), "Expected line to contain " + collectionLine3 + ", Actual " + result);
        assertTrue(result.endsWith(collectionEndOfLine), "Expected line to end with: " + collectionEndOfLine + " Actual " + result);
        for (final String frame : list) {
            int length = -1;
            final int frameLength = frame.length();
            final int firstSpacePosition = frame.indexOf(' ');
            final String messageLength = frame.substring(0, firstSpacePosition);
            try {
                length = Integer.parseInt(messageLength);
                // the ListAppender removes the ending newline, so we expect one less size
                assertEquals(frameLength, messageLength.length() + length);
            } catch (final NumberFormatException e) {
                fail("Not a valid RFC 5425 frame");
            }
        }
        appender.clear();
    } finally {
        root.removeAppender(appender);
        appender.stop();
    }
}
Also used : Appender(org.apache.logging.log4j.core.Appender) ListAppender(org.apache.logging.log4j.core.test.appender.ListAppender) StructuredDataMessage(org.apache.logging.log4j.message.StructuredDataMessage) ListAppender(org.apache.logging.log4j.core.test.appender.ListAppender) ArrayList(java.util.ArrayList) StructuredDataCollectionMessage(org.apache.logging.log4j.message.StructuredDataCollectionMessage) Test(org.junit.jupiter.api.Test)

Example 38 with ListAppender

use of org.apache.logging.log4j.core.test.appender.ListAppender in project logging-log4j2 by apache.

the class Rfc5424LayoutTest method testParameterizedMessage.

@Test
public void testParameterizedMessage() {
    for (final Appender appender : root.getAppenders().values()) {
        root.removeAppender(appender);
    }
    // set up appender
    final AbstractStringLayout layout = Rfc5424Layout.createLayout(Facility.LOCAL0, "Event", 3692, true, "RequestContext", null, null, true, null, "ATM", null, "key1, key2, locale", null, null, null, true, null, null);
    final ListAppender appender = new ListAppender("List", null, layout, true, false);
    appender.start();
    // set appender on root and set level to debug
    root.addAppender(appender);
    root.setLevel(Level.DEBUG);
    root.info("Hello {}", "World");
    try {
        final List<String> list = appender.getMessages();
        assertTrue(list.size() > 0, "Not enough list entries");
        final String message = list.get(0);
        assertTrue(message.contains("Hello World"), "Incorrect message. Expected - Hello World, Actual - " + message);
    } finally {
        root.removeAppender(appender);
        appender.stop();
    }
}
Also used : Appender(org.apache.logging.log4j.core.Appender) ListAppender(org.apache.logging.log4j.core.test.appender.ListAppender) ListAppender(org.apache.logging.log4j.core.test.appender.ListAppender) Test(org.junit.jupiter.api.Test)

Example 39 with ListAppender

use of org.apache.logging.log4j.core.test.appender.ListAppender in project logging-log4j2 by apache.

the class Rfc5424LayoutTest method testDiscardEmptyLoggerFields.

@Test
public void testDiscardEmptyLoggerFields() {
    final String mdcId = "RequestContext";
    for (final Appender appender : root.getAppenders().values()) {
        root.removeAppender(appender);
    }
    final LoggerFields[] loggerFields = new LoggerFields[] { LoggerFields.createLoggerFields(new KeyValuePair[] { new KeyValuePair("dummy", Strings.EMPTY), new KeyValuePair("empty", Strings.EMPTY) }, "SD-ID", "32473", true), LoggerFields.createLoggerFields(new KeyValuePair[] { new KeyValuePair("baz", "%C.%M"), new KeyValuePair("baz", "%C.%M") }, "BAZ", "32473", false), LoggerFields.createLoggerFields(new KeyValuePair[] { new KeyValuePair("bar", "%C.%M") }, null, null, false) };
    final AbstractStringLayout layout = Rfc5424Layout.createLayout(Facility.LOCAL0, "Event", 3692, true, mdcId, null, null, true, null, "ATM", null, "key1, key2, locale", null, null, null, false, loggerFields, null);
    final ListAppender appender = new ListAppender("List", null, layout, true, false);
    appender.start();
    root.addAppender(appender);
    root.setLevel(Level.DEBUG);
    root.info("starting logger fields test");
    try {
        final List<String> list = appender.getMessages();
        assertTrue(list.size() > 0, "Not enough list entries");
        final String message = list.get(0);
        assertFalse(message.contains("SD-ID"), "SD-ID should have been discarded");
        assertTrue(message.contains("BAZ"), "BAZ should have been included");
        assertTrue(message.contains(mdcId), mdcId + "should have been included");
        appender.clear();
    } finally {
        root.removeAppender(appender);
        appender.stop();
    }
}
Also used : Appender(org.apache.logging.log4j.core.Appender) ListAppender(org.apache.logging.log4j.core.test.appender.ListAppender) KeyValuePair(org.apache.logging.log4j.core.util.KeyValuePair) ListAppender(org.apache.logging.log4j.core.test.appender.ListAppender) Test(org.junit.jupiter.api.Test)

Example 40 with ListAppender

use of org.apache.logging.log4j.core.test.appender.ListAppender in project logging-log4j2 by apache.

the class SyslogLayoutTest method testLayout.

/**
 * Test case for MDC conversion pattern.
 */
@Test
public void testLayout() throws Exception {
    for (final Appender appender : root.getAppenders().values()) {
        root.removeAppender(appender);
    }
    // set up appender
    // @formatter:off
    final SyslogLayout layout = SyslogLayout.newBuilder().setFacility(Facility.LOCAL0).setIncludeNewLine(true).build();
    // @formatter:on
    // ConsoleAppender appender = new ConsoleAppender("Console", layout);
    final ListAppender appender = new ListAppender("List", null, layout, true, false);
    appender.start();
    // set appender on root and set level to debug
    root.addAppender(appender);
    root.setLevel(Level.DEBUG);
    // output starting message
    root.debug("starting mdc pattern test");
    root.debug("empty mdc");
    ThreadContext.put("key1", "value1");
    ThreadContext.put("key2", "value2");
    root.debug("filled mdc");
    ThreadContext.put("loginId", "JohnDoe");
    ThreadContext.put("ipAddress", "192.168.0.120");
    ThreadContext.put("locale", Locale.US.getDisplayName());
    final StructuredDataMessage msg = new StructuredDataMessage("Transfer@18060", "Transfer Complete", "Audit");
    msg.put("ToAccount", "123456");
    msg.put("FromAccount", "123457");
    msg.put("Amount", "200.00");
    root.info(MarkerManager.getMarker("EVENT"), msg);
    appender.stop();
    final List<String> list = appender.getMessages();
    assertTrue(list.get(0).endsWith(line1), "Expected line 1 to end with: " + line1 + " Actual " + list.get(0));
    assertTrue(list.get(1).endsWith(line2), "Expected line 2 to end with: " + line2 + " Actual " + list.get(1));
    assertTrue(list.get(2).endsWith(line3), "Expected line 3 to end with: " + line3 + " Actual " + list.get(2));
    assertTrue(list.get(3).endsWith(line4), "Expected line 4 to end with: " + line4 + " Actual " + list.get(3));
}
Also used : Appender(org.apache.logging.log4j.core.Appender) ListAppender(org.apache.logging.log4j.core.test.appender.ListAppender) StructuredDataMessage(org.apache.logging.log4j.message.StructuredDataMessage) ListAppender(org.apache.logging.log4j.core.test.appender.ListAppender) Test(org.junit.jupiter.api.Test)

Aggregations

ListAppender (org.apache.logging.log4j.core.test.appender.ListAppender)60 Test (org.junit.Test)24 Appender (org.apache.logging.log4j.core.Appender)21 Test (org.junit.jupiter.api.Test)15 Configuration (org.apache.logging.log4j.core.config.Configuration)6 StructuredDataMessage (org.apache.logging.log4j.message.StructuredDataMessage)5 AbstractLogger (org.apache.logging.log4j.spi.AbstractLogger)5 ConsoleAppender (org.apache.logging.log4j.core.appender.ConsoleAppender)4 KeyValuePair (org.apache.logging.log4j.core.util.KeyValuePair)4 AbstractJacksonLayout (org.apache.logging.log4j.jackson.AbstractJacksonLayout)4 Marker (org.apache.logging.log4j.Marker)3 LogEvent (org.apache.logging.log4j.core.LogEvent)3 Logger (org.apache.logging.log4j.core.Logger)3 DefaultConfiguration (org.apache.logging.log4j.core.config.DefaultConfiguration)3 ExtendedLogger (org.apache.logging.log4j.spi.ExtendedLogger)3 CountDownLatch (java.util.concurrent.CountDownLatch)2 Logger (java.util.logging.Logger)2 Log (org.apache.commons.logging.Log)2 LoggerContext (org.apache.logging.log4j.core.LoggerContext)2 RoutingAppender (org.apache.logging.log4j.core.appender.routing.RoutingAppender)2