org.apache.logging.log4j.util.SortedArrayStringMap Java Examples

The following examples show how to use org.apache.logging.log4j.util.SortedArrayStringMap. 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: ContextDataJsonAttributeConverterTest.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
@Test
public void testConvert02() {
    final StringMap map = new SortedArrayStringMap();
    map.putValue("someKey", "coolValue");
    map.putValue("anotherKey", "testValue");
    map.putValue("myKey", "yourValue");

    final String converted = this.converter.convertToDatabaseColumn(map);

    assertNotNull("The converted value should not be null.", converted);

    final ReadOnlyStringMap reversed = this.converter.convertToEntityAttribute(converted);

    assertNotNull("The reversed value should not be null.", reversed);
    assertEquals("The reversed value is not correct.", map, reversed);
}
 
Example #2
Source File: OpenCensusTraceContextDataInjectorTest.java    From opencensus-java with Apache License 2.0 6 votes vote down vote up
@Test
public void insertConfigurationProperties() {
  assertThat(
          new OpenCensusTraceContextDataInjector()
              .injectContextData(
                  Lists.newArrayList(
                      Property.createProperty("property1", "value1"),
                      Property.createProperty("property2", "value2")),
                  new SortedArrayStringMap())
              .toMap())
      .containsExactly(
          "property1",
          "value1",
          "property2",
          "value2",
          "traceId",
          "00000000000000000000000000000000",
          "spanId",
          "0000000000000000",
          "traceSampled",
          "false");
}
 
Example #3
Source File: JsonLayoutTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Test
public void testLayoutRingBufferEventReusableMessageWithCurlyBraces() throws Exception {
    final boolean propertiesAsList = false;
    final AbstractJacksonLayout layout = JsonLayout.newBuilder()
            .setLocationInfo(false)
            .setProperties(false)
            .setPropertiesAsList(propertiesAsList)
            .setComplete(false)
            .setCompact(true)
            .setEventEol(false)
            .setCharset(StandardCharsets.UTF_8)
            .setIncludeStacktrace(true)
            .build();
    Message message = ReusableMessageFactory.INSTANCE.newMessage("Testing {}", new TestObj());
    try {
        RingBufferLogEvent ringBufferEvent = new RingBufferLogEvent();
        ringBufferEvent.setValues(
                null, "a.B", null, "f.q.c.n", Level.DEBUG, message,
                null, new SortedArrayStringMap(), ThreadContext.EMPTY_STACK, 1L,
                "threadName", 1, null, new SystemClock(), new DummyNanoClock());
        final String str = layout.toSerializable(ringBufferEvent);
        final String expectedMessage = "Testing " + TestObj.TO_STRING_VALUE;
        assertThat(str, containsString("\"message\":\"" + expectedMessage + '"'));
        final Log4jLogEvent actual = new Log4jJsonObjectMapper(propertiesAsList, true, false, false).readValue(str, Log4jLogEvent.class);
        assertEquals(expectedMessage, actual.getMessage().getFormattedMessage());
    } finally {
        ReusableMessageFactory.release(message);
    }
}
 
Example #4
Source File: ContextDataJsonAttributeConverterTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Test
public void testConvert01() {
    final StringMap map = new SortedArrayStringMap();
    map.putValue("test1", "another1");
    map.putValue("key2", "value2");

    final String converted = this.converter.convertToDatabaseColumn(map);

    assertNotNull("The converted value should not be null.", converted);

    final ReadOnlyStringMap reversed = this.converter.convertToEntityAttribute(converted);

    assertNotNull("The reversed value should not be null.", reversed);
    assertEquals("The reversed value is not correct.", map, reversed);
}
 
Example #5
Source File: ContextDataAttributeConverterTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Test
public void testConvertToDatabaseColumn01() {
    final StringMap map = new SortedArrayStringMap();
    map.putValue("test1", "another1");
    map.putValue("key2", "value2");

    assertEquals("The converted value is not correct.", map.toString(),
            this.converter.convertToDatabaseColumn(map));
}
 
Example #6
Source File: JsonWriterTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Test
public void test_writeObject_IndexedReadOnlyStringMap() {
    final IndexedReadOnlyStringMap map =
            new SortedArrayStringMap(new LinkedHashMap<String, Object>() {{
                put("buzz", 1.2D);
                put("foo", "bar");
            }});
    final String expectedJson = "{'buzz':1.2,'foo':'bar'}".replace('\'', '"');
    final String actualJson = WRITER.use(() -> WRITER.writeObject(map));
    Assertions.assertThat(actualJson).isEqualTo(expectedJson);
}
 
Example #7
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 #8
Source File: MDCContextMap.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Override
public StringMap getReadOnlyContextData() {
    final Map<String, String> copy = getCopy();
    if (copy.isEmpty()) {
        return EMPTY_CONTEXT_DATA;
    }
    final StringMap result = new SortedArrayStringMap();
    for (final Entry<String, String> entry : copy.entrySet()) {
        result.putValue(entry.getKey(), entry.getValue());
    }
    return result;
}
 
Example #9
Source File: ContextDataFactory.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
public static StringMap createContextData() {
    if (DEFAULT_CONSTRUCTOR == null) {
        return new SortedArrayStringMap();
    }
    try {
        return (IndexedStringMap) DEFAULT_CONSTRUCTOR.newInstance();
    } catch (final Throwable ignored) {
        return new SortedArrayStringMap();
    }
}
 
Example #10
Source File: ContextDataFactory.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
public static StringMap createContextData(final int initialCapacity) {
    if (INITIAL_CAPACITY_CONSTRUCTOR == null) {
        return new SortedArrayStringMap(initialCapacity);
    }
    try {
        return (IndexedStringMap) INITIAL_CAPACITY_CONSTRUCTOR.newInstance(initialCapacity);
    } catch (final Throwable ignored) {
        return new SortedArrayStringMap(initialCapacity);
    }
}
 
Example #11
Source File: MapFilter.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
protected MapFilter(final Map<String, List<String>> map, final boolean oper, final Result onMatch, final Result onMismatch) {
    super(onMatch, onMismatch);
    this.isAnd = oper;
    Objects.requireNonNull(map, "map cannot be null");

    this.map = new SortedArrayStringMap(map.size());
    for (final Map.Entry<String, List<String>> entry : map.entrySet()) {
        this.map.putValue(entry.getKey(), entry.getValue());
    }
}
 
Example #12
Source File: ContextDataFactoryTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Test
public void intArgSetsCapacityIfNoPropertySpecified() throws Exception {
    final SortedArrayStringMap actual = (SortedArrayStringMap) ContextDataFactory.createContextData(2);
    final Field thresholdField = SortedArrayStringMap.class.getDeclaredField("threshold");
    thresholdField.setAccessible(true);
    assertEquals(2, thresholdField.getInt(actual));
}
 
Example #13
Source File: ContextDataFactoryPropertySetMissingConstructorTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Test
public void intArgReturnsSortedArrayStringMapIfPropertySpecifiedButMissingIntConstructor() throws Exception {
    System.setProperty("log4j2.ContextData", FactoryTestStringMapWithoutIntConstructor.class.getName());
    assertTrue(ContextDataFactory.createContextData(2) instanceof SortedArrayStringMap);
    final SortedArrayStringMap actual = (SortedArrayStringMap) ContextDataFactory.createContextData(2);
    final Field thresholdField = SortedArrayStringMap.class.getDeclaredField("threshold");
    thresholdField.setAccessible(true);
    assertEquals(2, thresholdField.getInt(actual));
    System.clearProperty("log4j2.ContextData");
}
 
Example #14
Source File: ThreadContextDataInjectorTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
private void testContextDataInjector() {
    ReadOnlyThreadContextMap readOnlythreadContextMap = getThreadContextMap();
    assertThat("thread context map class name",
               (readOnlythreadContextMap == null) ? null : readOnlythreadContextMap.getClass().getName(),
               is(equalTo(readOnlythreadContextMapClassName)));

    ContextDataInjector contextDataInjector = createInjector();
    StringMap stringMap = contextDataInjector.injectContextData(null, new SortedArrayStringMap());

    assertThat("thread context map", ThreadContext.getContext(), allOf(hasEntry("foo", "bar"), not(hasKey("baz"))));
    assertThat("context map", stringMap.toMap(), allOf(hasEntry("foo", "bar"), not(hasKey("baz"))));

    if (!stringMap.isFrozen()) {
        stringMap.clear();
        assertThat("thread context map", ThreadContext.getContext(), allOf(hasEntry("foo", "bar"), not(hasKey("baz"))));
        assertThat("context map", stringMap.toMap().entrySet(), is(empty()));
    }

    ThreadContext.put("foo", "bum");
    ThreadContext.put("baz", "bam");

    assertThat("thread context map", ThreadContext.getContext(), allOf(hasEntry("foo", "bum"), hasEntry("baz", "bam")));
    if (stringMap.isFrozen()) {
        assertThat("context map", stringMap.toMap(), allOf(hasEntry("foo", "bar"), not(hasKey("baz"))));
    } else {
        assertThat("context map", stringMap.toMap().entrySet(), is(empty()));
    }
}
 
Example #15
Source File: SortedArrayVsHashMapBenchmark.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Setup
public void setup() {
    openHashMapContextData = new OpenHashStringMap<>();
    sortedStringArrayMap = new SortedArrayStringMap();
    map = new HashMap<>();

    keys = new String[count];
    final Random r = new Random();
    for (int j = 0; j < keys.length; j++) {
        final char[] str = new char[length];
        for (int i = 0; i < str.length; i++) {
            str[i] = (char) r.nextInt();
        }
        keys[j] = new String(str);
    }

    populatedMap = new HashMap<>();
    for (int i = 0; i < count; i++) {
        populatedMap.put(keys[i], value);
    }
    populatedSortedStringArrayMap = new SortedArrayStringMap();
    for (int i = 0; i < count; i++) {
        populatedSortedStringArrayMap.putValue(keys[i], value);
    }
    populatedOpenHashContextData = new OpenHashStringMap<>();
    for (int i = 0; i < count; i++) {
        populatedOpenHashContextData.putValue(keys[i], value);
    }
}
 
Example #16
Source File: CustomFieldsConverterTest.java    From cf-java-logging-support with Apache License 2.0 5 votes vote down vote up
@Test
public void mergesMdcFieldsAndArguments() throws Exception {
	StringBuilder sb = new StringBuilder();
	when(event.getContextData()).thenReturn(new SortedArrayStringMap(MDC_PROPERTIES));
	CustomField customField = customField("some key", "some value");
	when(event.getMessage().getParameters()).thenReturn(new Object[] { customField });

	converter.format(event, sb);

	verifyConverterCall(allOf(hasEntry("this key", "this value"), hasEntry("that key", "that value"),
			not(hasEntry("other key", "other value"))), is(sameInstance(customField)));

}
 
Example #17
Source File: CustomFieldsConverterTest.java    From cf-java-logging-support with Apache License 2.0 5 votes vote down vote up
@Test
public void mdcFields() throws Exception {
	StringBuilder sb = new StringBuilder();
	when(event.getContextData()).thenReturn(new SortedArrayStringMap(MDC_PROPERTIES));
	when(event.getMessage().getParameters()).thenReturn(NO_PARAMETERS);

	converter.format(event, sb);

	verifyConverterCall(allOf(hasEntry("this key", "this value"), hasEntry("that key", "that value"),
			not(hasEntry("other key", "other value"))));
}
 
Example #18
Source File: CustomFieldsConverterTest.java    From cf-java-logging-support with Apache License 2.0 5 votes vote down vote up
@Test
public void singleCustomFieldArgument() throws Exception {
	StringBuilder sb = new StringBuilder();
	when(event.getContextData()).thenReturn(new SortedArrayStringMap());
	CustomField customField = customField("some key", "some value");
	when(event.getMessage().getParameters()).thenReturn(new Object[] { customField });

	converter.format(event, sb);

	verifyConverterCall(emptyMap(), is(sameInstance(customField)));
}
 
Example #19
Source File: CustomFieldsConverterTest.java    From cf-java-logging-support with Apache License 2.0 5 votes vote down vote up
@Test
public void standardArgument() throws Exception {
	StringBuilder sb = new StringBuilder();
	when(event.getContextData()).thenReturn(new SortedArrayStringMap());
	when(event.getMessage().getParameters()).thenReturn(new Object[] { "standard argument" });

	converter.format(event, sb);

	verifyConverterCall(emptyMap(), is("standard argument"));
}
 
Example #20
Source File: CustomFieldsConverterTest.java    From cf-java-logging-support with Apache License 2.0 5 votes vote down vote up
@Test
public void emptyMdcAndArguments() throws Exception {
	StringBuilder sb = new StringBuilder();
	when(event.getContextData()).thenReturn(new SortedArrayStringMap());
	when(event.getMessage().getParameters()).thenReturn(NO_PARAMETERS);

	converter.format(event, sb);

	verifyConverterCall(emptyMap());
}
 
Example #21
Source File: ContextDataFactoryTest.java    From logging-log4j2 with Apache License 2.0 4 votes vote down vote up
@Test
public void intArgReturnsSortedArrayStringMapIfNoPropertySpecified() throws Exception {
    assertTrue(ContextDataFactory.createContextData(2) instanceof SortedArrayStringMap);
}
 
Example #22
Source File: ContextDataFactoryTest.java    From logging-log4j2 with Apache License 2.0 4 votes vote down vote up
@Test
public void noArgReturnsSortedArrayStringMapIfNoPropertySpecified() throws Exception {
    assertTrue(ContextDataFactory.createContextData() instanceof SortedArrayStringMap);
}
 
Example #23
Source File: Log4jLogEventTest.java    From logging-log4j2 with Apache License 2.0 4 votes vote down vote up
@Test
public void testBuilderCorrectlyCopiesMutableLogEvent() throws Exception {
    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");
    new StackTraceElement("A", "B", "file", 123);
    final String fqcn = "qualified";
    final String name = "Ceci n'est pas une pipe";
    final String threadName = "threadName";
    final MutableLogEvent event = new MutableLogEvent();
    event.setContextData(contextData);
    event.setContextStack(contextStack);
    event.setEndOfBatch(true);
    event.setIncludeLocation(true);
    //event.setSource(stackTraceElement); // cannot be explicitly set
    event.setLevel(Level.FATAL);
    event.setLoggerFqcn(fqcn);
    event.setLoggerName(name);
    event.setMarker(marker);
    event.setMessage(message);
    event.setNanoTime(1234567890L);
    event.setThreadName(threadName);
    event.setThrown(exception);
    event.setTimeMillis(987654321L);

    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()); // don't invoke
    assertSame(threadName, event.getThreadName());
    assertSame(exception, event.getThrown());
    assertEquals(987654321L, event.getTimeMillis());

    final LogEvent e2 = new Log4jLogEvent.Builder(event).build();
    assertEquals(contextData, e2.getContextData());
    assertSame(contextStack, e2.getContextStack());
    assertEquals(true, e2.isEndOfBatch());
    assertEquals(true, e2.isIncludeLocation());
    assertSame(Level.FATAL, e2.getLevel());
    assertSame(fqcn, e2.getLoggerFqcn());
    assertSame(name, e2.getLoggerName());
    assertSame(marker, e2.getMarker());
    assertSame(message, e2.getMessage());
    assertEquals(1234567890L, e2.getNanoTime());
    //assertSame(stackTraceElement, e2.getSource()); // don't invoke
    assertSame(threadName, e2.getThreadName());
    assertSame(exception, e2.getThrown());
    assertEquals(987654321L, e2.getTimeMillis());

    // use reflection to get value of source field in log event copy:
    // invoking the getSource() method would initialize the field
    final Field fieldSource = Log4jLogEvent.class.getDeclaredField("source");
    fieldSource.setAccessible(true);
    final Object value = fieldSource.get(e2);
    assertNull("source in copy", value);
}
 
Example #24
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 #25
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 #26
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 #27
Source File: JsonWriterTest.java    From logging-log4j2 with Apache License 2.0 4 votes vote down vote up
@Test
public void test_writeObject_Map() {
    final Map<String, Object> map = new LinkedHashMap<String, Object>() {{
        put("key1", "val1");
        put("key2", Collections.singletonMap("key2.1", "val2.1"));
        put("key3", Arrays.asList(
                3,
                (byte) 127,
                4.5D,
                4.6F,
                Arrays.asList(true, false),
                new BigDecimal("30.12345678901234567890123456789"),
                new BigInteger("12345678901234567890123456789"),
                Collections.singleton('a'),
                Collections.singletonMap("key3.3", "val3.3")));
        put("key4", new LinkedHashMap<String, Object>() {{
            put("chars", new char[]{'a', 'b', 'c'});
            put("booleans", new boolean[]{true, false});
            put("bytes", new byte[]{1, 2});
            put("shorts", new short[]{3, 4});
            put("ints", new int[]{256, 257});
            put("longs", new long[]{2147483648L, 2147483649L});
            put("floats", new float[]{1.0F, 1.1F});
            put("doubles", new double[]{2.0D, 2.1D});
            put("objects", new Object[]{"foo", "bar"});
        }});
        put("key5\t", new Object() {
            @Override
            public String toString() {
                return "custom-object\r";
            }
        });
        put("key6", Arrays.asList(
                new SortedArrayStringMap(new LinkedHashMap<String, Object>() {{
                    put("buzz", 1.2D);
                    put("foo", "bar");
                }}),
                new JdkMapAdapterStringMap(Collections.singletonMap("a", "b"))));
        put("key7", (StringBuilderFormattable) buffer ->
                buffer.append(7.7777777777777D));
    }};
    final String expectedJson = ("{" +
            "'key1':'val1'," +
            "'key2':{'key2.1':'val2.1'}," +
            "'key3':[" +
            "3," +
            "127," +
            "4.5," +
            "4.6," +
            "[true,false]," +
            "30.12345678901234567890123456789," +
            "12345678901234567890123456789," +
            "['a']," +
            "{'key3.3':'val3.3'}" +
            "]," +
            "'key4':{" +
            "'chars':['a','b','c']," +
            "'booleans':[true,false]," +
            "'bytes':[1,2]," +
            "'shorts':[3,4]," +
            "'ints':[256,257]," +
            "'longs':[2147483648,2147483649]," +
            "'floats':[1.0,1.1]," +
            "'doubles':[2.0,2.1]," +
            "'objects':['foo','bar']" +
            "}," +
            "'key5\\t':'custom-object\\r'," +
            "'key6':[{'buzz':1.2,'foo':'bar'},{'a':'b'}]," +
            "'key7':'7.7777777777777'" +
            "}").replace('\'', '"');
    final String actualJson = WRITER.use(() -> WRITER.writeObject(map));
    Assertions.assertThat(actualJson).isEqualTo(expectedJson);
}
 
Example #28
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 #29
Source File: JsonTemplateLayoutTest.java    From logging-log4j2 with Apache License 2.0 4 votes vote down vote up
@Test
public void test_mdc_key_access() {

    // Create the log event.
    final SimpleMessage message = new SimpleMessage("Hello, World!");
    final StringMap contextData = new SortedArrayStringMap();
    final String mdcDirectlyAccessedKey = "mdcKey1";
    final String mdcDirectlyAccessedValue = "mdcValue1";
    contextData.putValue(mdcDirectlyAccessedKey, mdcDirectlyAccessedValue);
    final String mdcDirectlyAccessedNullPropertyKey = "mdcKey2";
    final String mdcDirectlyAccessedNullPropertyValue = null;
    // noinspection ConstantConditions
    contextData.putValue(mdcDirectlyAccessedNullPropertyKey, mdcDirectlyAccessedNullPropertyValue);
    final LogEvent logEvent = Log4jLogEvent
            .newBuilder()
            .setLoggerName(LOGGER_NAME)
            .setLevel(Level.INFO)
            .setMessage(message)
            .setContextData(contextData)
            .build();

    // Create the event template.
    String eventTemplate = writeJson(Map(
            mdcDirectlyAccessedKey, Map(
                    "$resolver", "mdc",
                    "key", mdcDirectlyAccessedKey),
            mdcDirectlyAccessedNullPropertyKey, Map(
                    "$resolver", "mdc",
                    "key", mdcDirectlyAccessedNullPropertyKey)));

    // 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(mdcDirectlyAccessedKey)).isEqualTo(mdcDirectlyAccessedValue);
        assertThat(accessor.getString(mdcDirectlyAccessedNullPropertyKey)).isNull();
    });

}
 
Example #30
Source File: PropertyRewritePolicy.java    From logging-log4j2 with Apache License 2.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
public LoggingEvent rewrite(final LoggingEvent source) {
    if (!properties.isEmpty()) {
        Map<String, String> rewriteProps = source.getProperties() != null ? new HashMap<>(source.getProperties())
                : new HashMap<>();
        for (Map.Entry<String, String> entry : properties.entrySet()) {
            if (!rewriteProps.containsKey(entry.getKey())) {
                rewriteProps.put(entry.getKey(), entry.getValue());
            }
        }
        LogEvent event;
        if (source instanceof LogEventAdapter) {
            event = new Log4jLogEvent.Builder(((LogEventAdapter) source).getEvent())
                    .setContextData(new SortedArrayStringMap(rewriteProps))
                    .build();
        } else {
            LocationInfo info = source.getLocationInformation();
            StackTraceElement element = new StackTraceElement(info.getClassName(), info.getMethodName(),
                    info.getFileName(), Integer.parseInt(info.getLineNumber()));
            Thread thread = getThread(source.getThreadName());
            long threadId = thread != null ? thread.getId() : 0;
            int threadPriority = thread != null ? thread.getPriority() : 0;
            event = Log4jLogEvent.newBuilder()
                    .setContextData(new SortedArrayStringMap(rewriteProps))
                    .setLevel(OptionConverter.convertLevel(source.getLevel()))
                    .setLoggerFqcn(source.getFQNOfLoggerClass())
                    .setMarker(null)
                    .setMessage(new SimpleMessage(source.getRenderedMessage()))
                    .setSource(element)
                    .setLoggerName(source.getLoggerName())
                    .setThreadName(source.getThreadName())
                    .setThreadId(threadId)
                    .setThreadPriority(threadPriority)
                    .setThrown(source.getThrowableInformation().getThrowable())
                    .setTimeMillis(source.getTimeStamp())
                    .setNanoTime(0)
                    .setThrownProxy(null)
                    .build();
        }
        return new LogEventAdapter(event);
    }
    return source;
}