Search in sources :

Example 6 with KeyValuePair

use of org.apache.logging.log4j.core.util.KeyValuePair in project logging-log4j2 by apache.

the class Rfc5424LayoutTest method testMDCLoggerFields.

/**
     * Test case for MDC logger field inclusion.
     */
@Test
public void testMDCLoggerFields() throws Exception {
    for (final Appender appender : root.getAppenders().values()) {
        root.removeAppender(appender);
    }
    final LoggerFields[] loggerFields = new LoggerFields[] { LoggerFields.createLoggerFields(new KeyValuePair[] { new KeyValuePair("source", "%C.%M") }, null, null, false), LoggerFields.createLoggerFields(new KeyValuePair[] { new KeyValuePair("source2", "%C.%M") }, null, null, false) };
    // set up layout/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, loggerFields, 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);
    // output starting message
    root.info("starting logger fields test");
    try {
        final List<String> list = appender.getMessages();
        assertTrue("Not enough list entries", list.size() > 0);
        assertTrue("No class/method", list.get(0).contains("Rfc5424LayoutTest.testMDCLoggerFields"));
        appender.clear();
    } finally {
        root.removeAppender(appender);
        appender.stop();
    }
}
Also used : Appender(org.apache.logging.log4j.core.Appender) ListAppender(org.apache.logging.log4j.test.appender.ListAppender) KeyValuePair(org.apache.logging.log4j.core.util.KeyValuePair) ListAppender(org.apache.logging.log4j.test.appender.ListAppender) Test(org.junit.Test)

Example 7 with KeyValuePair

use of org.apache.logging.log4j.core.util.KeyValuePair in project logging-log4j2 by apache.

the class Rfc5424LayoutTest method testLoggerFields.

@Test
public void testLoggerFields() {
    final String[] fields = new String[] { "[BAZ@32473 baz=\"org.apache.logging.log4j.core.layout.Rfc5424LayoutTest.testLoggerFields\"]", "[RequestContext@3692 bar=\"org.apache.logging.log4j.core.layout.Rfc5424LayoutTest.testLoggerFields\"]", "[SD-ID@32473 source=\"org.apache.logging.log4j.core.layout.Rfc5424LayoutTest.testLoggerFields\"]" };
    final List<String> expectedToContain = Arrays.asList(fields);
    for (final Appender appender : root.getAppenders().values()) {
        root.removeAppender(appender);
    }
    final LoggerFields[] loggerFields = new LoggerFields[] { LoggerFields.createLoggerFields(new KeyValuePair[] { new KeyValuePair("source", "%C.%M") }, "SD-ID", "32473", false), 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, "RequestContext", 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("Not enough list entries", list.size() > 0);
        final String message = list.get(0);
        assertTrue("No class/method", message.contains("Rfc5424LayoutTest.testLoggerFields"));
        for (final String value : expectedToContain) {
            Assert.assertTrue("Message expected to contain " + value + " but did not", message.contains(value));
        }
        appender.clear();
    } finally {
        root.removeAppender(appender);
        appender.stop();
    }
}
Also used : Appender(org.apache.logging.log4j.core.Appender) ListAppender(org.apache.logging.log4j.test.appender.ListAppender) KeyValuePair(org.apache.logging.log4j.core.util.KeyValuePair) ListAppender(org.apache.logging.log4j.test.appender.ListAppender) Test(org.junit.Test)

Example 8 with KeyValuePair

use of org.apache.logging.log4j.core.util.KeyValuePair in project logging-log4j2 by apache.

the class LoggerNameLevelRewritePolicyTest method testUpdate.

@Test
public void testUpdate() {
    final KeyValuePair[] rewrite = new KeyValuePair[] { new KeyValuePair("INFO", "DEBUG"), new KeyValuePair("WARN", "INFO") };
    final String loggerNameRewrite = "com.foo.bar";
    LogEvent logEvent = Log4jLogEvent.newBuilder().setLoggerName(loggerNameRewrite).setLoggerFqcn("LoggerNameLevelRewritePolicyTest.testUpdate()").setLevel(Level.INFO).setMessage(new SimpleMessage("Test")).setThrown(new RuntimeException("test")).setThreadName("none").setTimeMillis(1).build();
    final LoggerNameLevelRewritePolicy updatePolicy = LoggerNameLevelRewritePolicy.createPolicy(loggerNameRewrite, rewrite);
    LogEvent rewritten = updatePolicy.rewrite(logEvent);
    Assert.assertEquals(Level.DEBUG, rewritten.getLevel());
    logEvent = Log4jLogEvent.newBuilder().setLoggerName(loggerNameRewrite).setLoggerFqcn("LoggerNameLevelRewritePolicyTest.testUpdate()").setLevel(Level.WARN).setMessage(new SimpleMessage("Test")).setThrown(new RuntimeException("test")).setThreadName("none").setTimeMillis(1).build();
    rewritten = updatePolicy.rewrite(logEvent);
    Assert.assertEquals(Level.INFO, rewritten.getLevel());
    final String loggerNameReadOnly = "com.nochange";
    logEvent = Log4jLogEvent.newBuilder().setLoggerName(loggerNameReadOnly).setLoggerFqcn("LoggerNameLevelRewritePolicyTest.testUpdate()").setLevel(Level.INFO).setMessage(new SimpleMessage("Test")).setThrown(new RuntimeException("test")).setThreadName("none").setTimeMillis(1).build();
    rewritten = updatePolicy.rewrite(logEvent);
    Assert.assertEquals(Level.INFO, rewritten.getLevel());
    logEvent = Log4jLogEvent.newBuilder().setLoggerName(loggerNameReadOnly).setLoggerFqcn("LoggerNameLevelRewritePolicyTest.testUpdate()").setLevel(Level.WARN).setMessage(new SimpleMessage("Test")).setThrown(new RuntimeException("test")).setThreadName("none").setTimeMillis(1).build();
    rewritten = updatePolicy.rewrite(logEvent);
    Assert.assertEquals(Level.WARN, rewritten.getLevel());
}
Also used : KeyValuePair(org.apache.logging.log4j.core.util.KeyValuePair) Log4jLogEvent(org.apache.logging.log4j.core.impl.Log4jLogEvent) LogEvent(org.apache.logging.log4j.core.LogEvent) SimpleMessage(org.apache.logging.log4j.message.SimpleMessage) Test(org.junit.Test)

Example 9 with KeyValuePair

use of org.apache.logging.log4j.core.util.KeyValuePair in project logging-log4j2 by apache.

the class MapRewritePolicy method createPolicy.

/**
     * The factory method to create the MapRewritePolicy.
     * @param mode The string representation of the Mode.
     * @param pairs key/value pairs for the new Map keys and values.
     * @return The MapRewritePolicy.
     */
@PluginFactory
public static MapRewritePolicy createPolicy(@PluginAttribute("mode") final String mode, @PluginElement("KeyValuePair") final KeyValuePair[] pairs) {
    Mode op = mode == null ? op = Mode.Add : Mode.valueOf(mode);
    if (pairs == null || pairs.length == 0) {
        LOGGER.error("keys and values must be specified for the MapRewritePolicy");
        return null;
    }
    final Map<String, String> map = new HashMap<>();
    for (final KeyValuePair pair : pairs) {
        final String key = pair.getKey();
        if (key == null) {
            LOGGER.error("A null key is not valid in MapRewritePolicy");
            continue;
        }
        final String value = pair.getValue();
        if (value == null) {
            LOGGER.error("A null value for key " + key + " is not allowed in MapRewritePolicy");
            continue;
        }
        map.put(pair.getKey(), pair.getValue());
    }
    if (map.isEmpty()) {
        LOGGER.error("MapRewritePolicy is not configured with any valid key value pairs");
        return null;
    }
    return new MapRewritePolicy(map, op);
}
Also used : KeyValuePair(org.apache.logging.log4j.core.util.KeyValuePair) HashMap(java.util.HashMap) PluginFactory(org.apache.logging.log4j.core.config.plugins.PluginFactory)

Example 10 with KeyValuePair

use of org.apache.logging.log4j.core.util.KeyValuePair 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) 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).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);
}
Also used : ListAppender(org.apache.logging.log4j.test.appender.ListAppender) EncodingListAppender(org.apache.logging.log4j.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.test.appender.EncodingListAppender) IOException(java.io.IOException) GZIPInputStream(java.util.zip.GZIPInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) ListAppender(org.apache.logging.log4j.test.appender.ListAppender) EncodingListAppender(org.apache.logging.log4j.test.appender.EncodingListAppender)

Aggregations

KeyValuePair (org.apache.logging.log4j.core.util.KeyValuePair)15 Test (org.junit.Test)7 HashMap (java.util.HashMap)5 PluginFactory (org.apache.logging.log4j.core.config.plugins.PluginFactory)5 ListAppender (org.apache.logging.log4j.test.appender.ListAppender)4 ArrayList (java.util.ArrayList)3 List (java.util.List)3 Appender (org.apache.logging.log4j.core.Appender)3 Log4jLogEvent (org.apache.logging.log4j.core.impl.Log4jLogEvent)3 SimpleMessage (org.apache.logging.log4j.message.SimpleMessage)3 LogEvent (org.apache.logging.log4j.core.LogEvent)2 MapMessage (org.apache.logging.log4j.message.MapMessage)2 StructuredDataMessage (org.apache.logging.log4j.message.StructuredDataMessage)2 ByteArrayInputStream (java.io.ByteArrayInputStream)1 IOException (java.io.IOException)1 InputStream (java.io.InputStream)1 GZIPInputStream (java.util.zip.GZIPInputStream)1 InflaterInputStream (java.util.zip.InflaterInputStream)1 Level (org.apache.logging.log4j.Level)1 JavaLookup (org.apache.logging.log4j.core.lookup.JavaLookup)1