Java Code Examples for org.apache.logging.log4j.util.StringMap#putValue()

The following examples show how to use org.apache.logging.log4j.util.StringMap#putValue() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: PatternParserTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Test
public void testDeeplyNestedPattern() {
    final List<PatternFormatter> formatters = parser.parse(deeplyNestedPattern);
    assertNotNull(formatters);
    assertEquals(1, formatters.size());

    final StringMap mdc = ContextDataFactory.createContextData();
    mdc.putValue("var", "1234");
    final Log4jLogEvent event = Log4jLogEvent.newBuilder() //
        .setContextData(mdc).build();
    final StringBuilder buf = new StringBuilder();
    formatters.get(0).format(event, buf);
    final String expected = " 123 ";
    assertEquals(expected, buf.toString());
}
 
Example 2
Source File: ThreadContextDataInjector.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
/**
 * Copies key-value pairs from the specified property list into the specified {@code StringMap}.
 *
 * @param properties list of configuration properties, may be {@code null}
 * @param result the {@code StringMap} object to add the key-values to. Must be non-{@code null}.
 */
public static void copyProperties(final List<Property> properties, final StringMap result) {
    if (properties != null) {
        for (int i = 0; i < properties.size(); i++) {
            final Property prop = properties.get(i);
            result.putValue(prop.getName(), prop.getValue());
        }
    }
}
 
Example 3
Source File: ContextDataAttributeConverterTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Test
public void testConvertToDatabaseColumn02() {
    final StringMap map = new SortedArrayStringMap();
    map.putValue("someKey", "coolValue");
    map.putValue("anotherKey", "testValue");
    map.putValue("myKey", "yourValue");

    assertEquals("The converted value is not correct.", map.toString(),
            this.converter.convertToDatabaseColumn(map));
}
 
Example 4
Source File: Log4jLogEvent.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
private static StringMap createContextData(final Map<String, String> contextMap) {
    final StringMap result = ContextDataFactory.createContextData();
    if (contextMap != null) {
        for (final Map.Entry<String, String> entry : contextMap.entrySet()) {
            result.putValue(entry.getKey(), entry.getValue());
        }
    }
    return result;
}
 
Example 5
Source File: Log4j1XmlLayoutTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Test
public void testWithPropertiesAndLocationInfo() {
    final Log4j1XmlLayout layout = Log4j1XmlLayout.createLayout(true, true);

    final StringMap contextMap = ContextDataFactory.createContextData(2);
    contextMap.putValue("key1", "value1");
    contextMap.putValue("key2", "value2");
    final Log4jLogEvent event = Log4jLogEvent.newBuilder()
            .setLoggerName("a.B")
            .setLevel(Level.INFO)
            .setMessage(new SimpleMessage("Hello, World"))
            .setTimeMillis(System.currentTimeMillis() + 17)
            .setIncludeLocation(true)
            .setSource(new StackTraceElement("pack.MyClass", "myMethod", "MyClass.java", 17))
            .setContextData(contextMap)
            .build();

    final String result = layout.toSerializable(event);

    final String expected =
            "<log4j:event logger=\"a.B\" timestamp=\"" + event.getTimeMillis() + "\" level=\"INFO\" thread=\"main\">\r\n" +
            "<log4j:message><![CDATA[Hello, World]]></log4j:message>\r\n" +
            "<log4j:locationInfo class=\"pack.MyClass\" method=\"myMethod\" file=\"MyClass.java\" line=\"17\"/>\r\n" +
            "<log4j:properties>\r\n" +
            "<log4j:data name=\"key1\" value=\"value1\"/>\r\n" +
            "<log4j:data name=\"key2\" value=\"value2\"/>\r\n" +
            "</log4j:properties>\r\n"+
            "</log4j:event>\r\n\r\n";

    assertEquals(expected, result);
}
 
Example 6
Source File: Log4j1MdcPatternConverterTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Test
public void testConverter2() {
    final StringMap contextMap = ContextDataFactory.createContextData(2);
    contextMap.putValue("key1", "value1");
    contextMap.putValue("key2", "value2");
    final String expected = "{{key1,value1}{key2,value2}}";
    test(contextMap, expected, null);
}
 
Example 7
Source File: Log4j1MdcPatternConverterTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Test
public void testConverter1() {
    final StringMap contextMap = ContextDataFactory.createContextData(1);
    contextMap.putValue("key1", "value1");
    final String expected = "{{key1,value1}}";
    test(contextMap, expected, null);
}
 
Example 8
Source File: Log4j1MdcPatternConverterTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Test
public void testConverter2() {
    final StringMap contextMap = ContextDataFactory.createContextData(2);
    contextMap.putValue("key1", "value1");
    contextMap.putValue("key2", "value2");
    final String expected = "{{key1,value1}{key2,value2}}";
    test(contextMap, expected, null);
}
 
Example 9
Source File: Log4j1MdcPatternConverterTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Test
public void testConverter1() {
    final StringMap contextMap = ContextDataFactory.createContextData(1);
    contextMap.putValue("key1", "value1");
    final String expected = "{{key1,value1}}";
    test(contextMap, expected, null);
}
 
Example 10
Source File: PatternParserTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
/**
 * Test the custom pattern
 */
@Test
public void testCustomPattern() {
    final List<PatternFormatter> formatters = parser.parse(customPattern);
    assertNotNull(formatters);
    final StringMap mdc = ContextDataFactory.createContextData();
    mdc.putValue("loginId", "Fred");
    final Throwable t = new Throwable();
    final StackTraceElement[] elements = t.getStackTrace();
    final Log4jLogEvent event = Log4jLogEvent.newBuilder() //
            .setLoggerName("org.apache.logging.log4j.PatternParserTest") //
            .setMarker(MarkerManager.getMarker("TEST")) //
            .setLoggerFqcn(Logger.class.getName()) //
            .setLevel(Level.INFO) //
            .setMessage(new SimpleMessage("Hello, world")) //
            .setContextData(mdc) //
            .setThreadName("Thread1") //
            .setSource(elements[0])
            .setTimeMillis(System.currentTimeMillis()).build();
    final StringBuilder buf = new StringBuilder();
    for (final PatternFormatter formatter : formatters) {
        formatter.format(event, buf);
    }
    final String str = buf.toString();
    final String expected = "INFO  [PatternParserTest        :104 ] - Hello, world" + Strings.LINE_SEPARATOR;
    assertTrue("Expected to end with: " + expected + ". Actual: " + str, str.endsWith(expected));
}
 
Example 11
Source File: CopyOnWriteSortedArrayThreadContextMap.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Override
public void putAll(final Map<String, String> values) {
    if (values == null || values.isEmpty()) {
        return;
    }
    StringMap map = localMap.get();
    map = map == null ? createStringMap() : createStringMap(map);
    for (final Map.Entry<String, String> entry : values.entrySet()) {
        map.putValue(entry.getKey(), entry.getValue());
    }
    map.freeze();
    localMap.set(map);
}
 
Example 12
Source File: CopyOnWriteSortedArrayThreadContextMap.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Override
public void putValue(final String key, final Object value) {
    StringMap map = localMap.get();
    map = map == null ? createStringMap() : createStringMap(map);
    map.putValue(key, value);
    map.freeze();
    localMap.set(map);
}
 
Example 13
Source File: ContextDataFactory.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
public static StringMap createContextData(final Map<String, String> context) {
    final StringMap contextData = createContextData(context.size());
    for (Entry<String, String> entry : context.entrySet()) {
        contextData.putValue(entry.getKey(), entry.getValue());
    }
    return contextData;
}
 
Example 14
Source File: GarbageFreeSortedArrayThreadContextMap.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Override
public void putAll(final Map<String, String> values) {
    if (values == null || values.isEmpty()) {
        return;
    }
    final StringMap map = getThreadLocalMap();
    for (final Map.Entry<String, String> entry : values.entrySet()) {
        map.putValue(entry.getKey(), entry.getValue());
    }
}
 
Example 15
Source File: LogEventFixtures.java    From logging-log4j2 with Apache License 2.0 4 votes vote down vote up
/**
 * @return a log event that uses all the bells and whistles, features, nooks and crannies
 */
public static Log4jLogEvent createLogEvent() {
    final Marker cMarker = MarkerManager.getMarker("Marker1");
    final Marker pMarker1 = MarkerManager.getMarker("ParentMarker1");
    final Marker pMarker2 = MarkerManager.getMarker("ParentMarker2");
    final Marker gfMarker = MarkerManager.getMarker("GrandFatherMarker");
    final Marker gmMarker = MarkerManager.getMarker("GrandMotherMarker");
    cMarker.addParents(pMarker1);
    cMarker.addParents(pMarker2);
    pMarker1.addParents(gmMarker);
    pMarker1.addParents(gfMarker);
    final Exception sourceHelper = new Exception();
    sourceHelper.fillInStackTrace();
    final Exception cause = new NullPointerException("testNPEx");
    sourceHelper.fillInStackTrace();
    final StackTraceElement source = sourceHelper.getStackTrace()[0];
    final IOException ioException = new IOException("testIOEx", cause);
    ioException.addSuppressed(new IndexOutOfBoundsException("I am suppressed exception 1"));
    ioException.addSuppressed(new IndexOutOfBoundsException("I am suppressed exception 2"));
    final ThrowableProxy throwableProxy = new ThrowableProxy(ioException);
    final StringMap contextData = ContextDataFactory.createContextData();
    contextData.putValue("MDC.A", "A_Value");
    contextData.putValue("MDC.B", "B_Value");
    final DefaultThreadContextStack contextStack = new DefaultThreadContextStack(true);
    contextStack.clear();
    contextStack.push("stack_msg1");
    contextStack.add("stack_msg2");
    final Log4jLogEvent expected = Log4jLogEvent.newBuilder() //
            .setLoggerName("a.B") //
            .setMarker(cMarker) //
            .setLoggerFqcn("f.q.c.n") //
            .setLevel(Level.DEBUG) //
            .setMessage(new SimpleMessage("Msg")) //
            .setThrown(ioException) //
            .setThrownProxy(throwableProxy) //
            .setContextData(contextData) //
            .setContextStack(contextStack) //
            .setThreadName("MyThreadName") //
            .setSource(source) //
            .setTimeMillis(1).build();
    // validate event?
    return expected;
}
 
Example 16
Source File: Log4jLogEventTest.java    From logging-log4j2 with Apache License 2.0 4 votes vote down vote up
@Test
public void testBuilderCorrectlyCopiesAllEventAttributesInclContextData() {
    final StringMap contextData = new SortedArrayStringMap();
    contextData.putValue("A", "B");
    final ContextStack contextStack = ThreadContext.getImmutableStack();
    final Exception exception = new Exception("test");
    final Marker marker = MarkerManager.getMarker("EVENTTEST");
    final Message message = new SimpleMessage("foo");
    final StackTraceElement stackTraceElement = new StackTraceElement("A", "B", "file", 123);
    final String fqcn = "qualified";
    final String name = "Ceci n'est pas une pipe";
    final String threadName = "threadName";
    final Log4jLogEvent event = Log4jLogEvent.newBuilder() //
            .setContextData(contextData) //
            .setContextStack(contextStack) //
            .setEndOfBatch(true) //
            .setIncludeLocation(true) //
            .setLevel(Level.FATAL) //
            .setLoggerFqcn(fqcn) //
            .setLoggerName(name) //
            .setMarker(marker) //
            .setMessage(message) //
            .setNanoTime(1234567890L) //
            .setSource(stackTraceElement) //
            .setThreadName(threadName) //
            .setThrown(exception) //
            .setTimeMillis(987654321L)
            .build();

    assertSame(contextData, event.getContextData());
    assertSame(contextStack, event.getContextStack());
    assertEquals(true, event.isEndOfBatch());
    assertEquals(true, event.isIncludeLocation());
    assertSame(Level.FATAL, event.getLevel());
    assertSame(fqcn, event.getLoggerFqcn());
    assertSame(name, event.getLoggerName());
    assertSame(marker, event.getMarker());
    assertSame(message, event.getMessage());
    assertEquals(1234567890L, event.getNanoTime());
    assertSame(stackTraceElement, event.getSource());
    assertSame(threadName, event.getThreadName());
    assertSame(exception, event.getThrown());
    assertEquals(987654321L, event.getTimeMillis());

    final LogEvent event2 = new Log4jLogEvent.Builder(event).build();
    assertEquals("copy constructor builder", event2, event);
    assertEquals("same hashCode", event2.hashCode(), event.hashCode());
}
 
Example 17
Source File: MutableLogEventTest.java    From logging-log4j2 with Apache License 2.0 4 votes vote down vote up
private static StringMap createContextData() {
    final StringMap result = new SortedArrayStringMap();
    result.putValue("a", "1");
    result.putValue("b", "2");
    return result;
}
 
Example 18
Source File: JsonTemplateLayoutTest.java    From logging-log4j2 with Apache License 2.0 4 votes vote down vote up
@Test
public void test_mdc_pattern() {

    // Create the log event.
    final SimpleMessage message = new SimpleMessage("Hello, World!");
    final StringMap contextData = new SortedArrayStringMap();
    final String mdcPatternMatchedKey = "mdcKey1";
    final String mdcPatternMatchedValue = "mdcValue1";
    contextData.putValue(mdcPatternMatchedKey, mdcPatternMatchedValue);
    final String mdcPatternMismatchedKey = "mdcKey2";
    final String mdcPatternMismatchedValue = "mdcValue2";
    contextData.putValue(mdcPatternMismatchedKey, mdcPatternMismatchedValue);
    final LogEvent logEvent = Log4jLogEvent
            .newBuilder()
            .setLoggerName(LOGGER_NAME)
            .setLevel(Level.INFO)
            .setMessage(message)
            .setContextData(contextData)
            .build();

    // Create the event template.
    final String mdcFieldName = "mdc";
    final String eventTemplate = writeJson(Map(
            mdcFieldName, Map(
                    "$resolver", "mdc",
                    "pattern", mdcPatternMatchedKey)));

    // Create the layout.
    final JsonTemplateLayout layout = JsonTemplateLayout
            .newBuilder()
            .setConfiguration(CONFIGURATION)
            .setStackTraceEnabled(true)
            .setEventTemplate(eventTemplate)
            .build();

    // Check the serialized event.
    usingSerializedLogEventAccessor(layout, logEvent, accessor -> {
        assertThat(accessor.getString(new String[]{mdcFieldName, mdcPatternMatchedKey})).isEqualTo(mdcPatternMatchedValue);
        assertThat(accessor.exists(new String[]{mdcFieldName, mdcPatternMismatchedKey})).isFalse();
    });

}
 
Example 19
Source File: JsonTemplateLayoutTest.java    From logging-log4j2 with Apache License 2.0 4 votes vote down vote up
@Test
public void test_mdc_flatten() {

    // Create the log event.
    final SimpleMessage message = new SimpleMessage("Hello, World!");
    final StringMap contextData = new SortedArrayStringMap();
    final String mdcPatternMatchedKey = "mdcKey1";
    final String mdcPatternMatchedValue = "mdcValue1";
    contextData.putValue(mdcPatternMatchedKey, mdcPatternMatchedValue);
    final String mdcPatternMismatchedKey = "mdcKey2";
    final String mdcPatternMismatchedValue = "mdcValue2";
    contextData.putValue(mdcPatternMismatchedKey, mdcPatternMismatchedValue);
    final LogEvent logEvent = Log4jLogEvent
            .newBuilder()
            .setLoggerName(LOGGER_NAME)
            .setLevel(Level.INFO)
            .setMessage(message)
            .setContextData(contextData)
            .build();

    // Create the event template.
    final String mdcPrefix = "_mdc.";
    final String eventTemplate = writeJson(Map(
            "ignoredFieldName", Map(
                    "$resolver", "mdc",
                    "pattern", mdcPatternMatchedKey,
                    "flatten", Map("prefix", mdcPrefix))));

    // Create the layout.
    final JsonTemplateLayout layout = JsonTemplateLayout
            .newBuilder()
            .setConfiguration(CONFIGURATION)
            .setStackTraceEnabled(true)
            .setEventTemplate(eventTemplate)
            .build();

    // Check the serialized event.
    usingSerializedLogEventAccessor(layout, logEvent, accessor -> {
        assertThat(accessor.getString(mdcPrefix + mdcPatternMatchedKey)).isEqualTo(mdcPatternMatchedValue);
        assertThat(accessor.exists(mdcPrefix + mdcPatternMismatchedKey)).isFalse();
    });

}
 
Example 20
Source File: ContextDataUtils.java    From opencensus-java with Apache License 2.0 4 votes vote down vote up
private static void putProperties(Collection<Property> properties, StringMap stringMap) {
  for (Property property : properties) {
    stringMap.putValue(property.getName(), property.getValue());
  }
}