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

The following examples show how to use org.apache.logging.log4j.util.StringMap. 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: TextEncoderHelperBenchmark.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
private static LogEvent createLogEvent() {
    final Marker marker = null;
    final String fqcn = "com.mycom.myproject.mypackage.MyClass";
    final Level level = Level.DEBUG;
    final Message message = new SimpleMessage(STR);
    final Throwable t = null;
    final StringMap mdc = null;
    final ContextStack ndc = null;
    final String threadName = null;
    final StackTraceElement location = null;
    final long timestamp = 12345678;

    return Log4jLogEvent.newBuilder() //
            .setLoggerName("name(ignored)") //
            .setMarker(marker) //
            .setLoggerFqcn(fqcn) //
            .setLevel(level) //
            .setMessage(message) //
            .setThrown(t) //
            .setContextData(mdc) //
            .setContextStack(ndc) //
            .setThreadName(threadName) //
            .setSource(location) //
            .setTimeMillis(timestamp) //
            .build();
}
 
Example #2
Source File: GelfLayoutBenchmark.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
private static LogEvent createLogEvent() {
    final Marker marker = null;
    final String fqcn = "com.mycom.myproject.mypackage.MyClass";
    final org.apache.logging.log4j.Level level = org.apache.logging.log4j.Level.DEBUG;
    final Message message = new SimpleMessage(MESSAGE);
    final Throwable t = null;
    final StringMap mdc = null;
    final ThreadContext.ContextStack ndc = null;
    final String threadName = null;
    final StackTraceElement location = null;
    final long timestamp = 12345678;

    return Log4jLogEvent.newBuilder() //
            .setLoggerName("name(ignored)") //
            .setMarker(marker) //
            .setLoggerFqcn(fqcn) //
            .setLevel(level) //
            .setMessage(message) //
            .setThrown(t) //
            .setContextData(mdc) //
            .setContextStack(ndc) //
            .setThreadName(threadName) //
            .setSource(location) //
            .setTimeMillis(timestamp) //
            .build();
}
 
Example #3
Source File: RingBufferLogEventTest.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetMillisReturnsConstructorMillisForNormalMessage() {
    final RingBufferLogEvent evt = new RingBufferLogEvent();
    final String loggerName = null;
    final Marker marker = null;
    final String fqcn = null;
    final Level level = null;
    final Message data = null;
    final Throwable t = null;
    final ContextStack contextStack = null;
    final String threadName = null;
    final StackTraceElement location = null;
    evt.setValues(null, loggerName, marker, fqcn, level, data, t, (StringMap) evt.getContextData(),
            contextStack, -1, threadName, -1, location, new FixedPreciseClock(123, 456), new DummyNanoClock(1));
    assertEquals(123, evt.getTimeMillis());
    assertEquals(456, evt.getInstant().getNanoOfMillisecond());
}
 
Example #4
Source File: ContextDataJsonAttributeConverter.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
@Override
public ReadOnlyStringMap convertToEntityAttribute(final String s) {
    if (Strings.isEmpty(s)) {
        return null;
    }
    try {
        final StringMap result = ContextDataFactory.createContextData();
        final ObjectNode root = (ObjectNode) OBJECT_MAPPER.readTree(s);
        final Iterator<Map.Entry<String, JsonNode>> entries = root.fields();
        while (entries.hasNext()) {
            final Map.Entry<String, JsonNode> entry = entries.next();

            // Don't know what to do with non-text values.
            // Maybe users who need this need to provide custom converter?
            final Object value = entry.getValue().textValue();
            result.putValue(entry.getKey(), value);
        }
        return result;
    } catch (final IOException e) {
        throw new PersistenceException("Failed to convert JSON string to map.", e);
    }
}
 
Example #5
Source File: ContextDataDeserializer.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
@Override
    public StringMap deserialize(final JsonParser jp, final DeserializationContext ctxt) throws IOException,
            JsonProcessingException {

        // Sanity check: verify that we got "Json Object":
//        JsonToken tok = jp.nextToken();
//        if (tok != JsonToken.START_OBJECT) {
//            throw new IOException("Expected data to start with an Object");
//        }
        final StringMap contextData = ContextDataFactory.createContextData();
        // Iterate over object fields:
        while (jp.nextToken() != JsonToken.END_OBJECT) {
            final String fieldName = jp.getCurrentName();

            // move to value
            jp.nextToken();
            contextData.putValue(fieldName, jp.getText());
        }
        return contextData;
    }
 
Example #6
Source File: ThreadContextDataInjector.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
/**
 * If there are no configuration properties, this injector will return the thread context's internal data
 * structure. Otherwise the configuration properties are combined with the thread context key-value pairs into the
 * specified reusable StringMap.
 *
 * @param props list of configuration properties, may be {@code null}
 * @param ignore a {@code StringMap} instance from the log event
 * @return a {@code StringMap} combining configuration properties with thread context data
 */
@Override
public StringMap injectContextData(final List<Property> props, final StringMap ignore) {
    // If there are no configuration properties we want to just return the ThreadContext's StringMap:
    // it is a copy-on-write data structure so we are sure ThreadContext changes will not affect our copy.
    if (providers.size() == 1 && (props == null || props.isEmpty())) {
        // this will replace the LogEvent's context data with the returned instance
        return providers.get(0).supplyStringMap();
    }
    int count = props == null ? 0 : props.size();
    StringMap[] maps = new StringMap[providers.size()];
    for (int i = 0; i < providers.size(); ++i) {
        maps[i] = providers.get(i).supplyStringMap();
        count += maps[i].size();
    }
    // However, if the list of Properties is non-empty we need to combine the properties and the ThreadContext
    // data. Note that we cannot reuse the specified StringMap: some Loggers may have properties defined
    // and others not, so the LogEvent's context data may have been replaced with an immutable copy from
    // the ThreadContext - this will throw an UnsupportedOperationException if we try to modify it.
    final StringMap result = ContextDataFactory.createContextData(count);
    copyProperties(props, result);
    for (StringMap map : maps) {
        result.putAll(map);
    }
    return result;
}
 
Example #7
Source File: Log4jLogEvent.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
private Log4jLogEvent(final String loggerName, final Marker marker, final String loggerFQCN, final Level level,
                      final Message message, final Throwable thrown, final ThrowableProxy thrownProxy,
                      final StringMap contextData, final ThreadContext.ContextStack contextStack, final long threadId,
                      final String threadName, final int threadPriority, final StackTraceElement source,
                      final long nanoTime) {
    this.loggerName = loggerName;
    this.marker = marker;
    this.loggerFqcn = loggerFQCN;
    this.level = level == null ? Level.OFF : level; // LOG4J2-462, LOG4J2-465
    this.message = message;
    this.thrown = thrown;
    this.thrownProxy = thrownProxy;
    this.contextData = contextData == null ? ContextDataFactory.createContextData() : contextData;
    this.contextStack = contextStack == null ? ThreadContext.EMPTY_STACK : contextStack;
    this.threadId = threadId;
    this.threadName = threadName;
    this.threadPriority = threadPriority;
    this.source = source;
    if (message instanceof LoggerNameAwareMessage) {
        ((LoggerNameAwareMessage) message).setLoggerName(loggerName);
    }
    this.nanoTime = nanoTime;
}
 
Example #8
Source File: AbstractStringLayoutStringEncodingBenchmark.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
private static LogEvent createLogEvent(final Message message) {
    final Marker marker = null;
    final String fqcn = "com.mycom.myproject.mypackage.MyClass";
    final org.apache.logging.log4j.Level level = org.apache.logging.log4j.Level.DEBUG;
    final Throwable t = null;
    final StringMap mdc = null;
    final ThreadContext.ContextStack ndc = null;
    final String threadName = null;
    final StackTraceElement location = null;
    final long timestamp = 12345678;

    return Log4jLogEvent.newBuilder() //
        .setLoggerName("name(ignored)") //
        .setMarker(marker) //
        .setLoggerFqcn(fqcn) //
        .setLevel(level) //
        .setMessage(message) //
        .setThrown(t) //
        .setContextData(mdc) //
        .setContextStack(ndc) //
        .setThreadName(threadName) //
        .setSource(location) //
        .setTimeMillis(timestamp) //
        .build();
}
 
Example #9
Source File: PatternLayoutComparisonBenchmark.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
private static LogEvent createLog4j2Event() {
    final Marker marker = null;
    final String fqcn = "com.mycom.myproject.mypackage.MyClass";
    final Level level = Level.DEBUG;
    final Message message = new SimpleMessage(STR);
    final Throwable t = null;
    final StringMap mdc = null;
    final ContextStack ndc = null;
    final String threadName = null;
    final StackTraceElement location = null;
    final long timestamp = 12345678;

    return Log4jLogEvent.newBuilder() //
            .setLoggerName("name(ignored)") //
            .setMarker(marker) //
            .setLoggerFqcn(fqcn) //
            .setLevel(level) //
            .setMessage(message) //
            .setThrown(t) //
            .setContextData(mdc) //
            .setContextStack(ndc) //
            .setThreadName(threadName) //
            .setSource(location) //
            .setTimeMillis(timestamp) //
            .build();
}
 
Example #10
Source File: Log4j2AppenderComparisonBenchmark.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
private static LogEvent createLogEvent() {
    final Marker marker = null;
    final String fqcn = "com.mycom.myproject.mypackage.MyClass";
    final Level level = Level.DEBUG;
    final Message message = new SimpleMessage(MESSAGE);
    final Throwable t = null;
    final StringMap mdc = null;
    final ThreadContext.ContextStack ndc = null;
    final String threadName = "THREAD";
    final StackTraceElement location = null;
    final long timestamp = System.currentTimeMillis();

    return Log4jLogEvent.newBuilder() //
            .setLoggerName("name(ignored)") //
            .setMarker(marker) //
            .setLoggerFqcn(fqcn) //
            .setLevel(level) //
            .setMessage(message) //
            .setThrown(t) //
            .setContextData(mdc) //
            .setContextStack(ndc) //
            .setThreadName(threadName) //
            .setSource(location) //
            .setTimeMillis(timestamp) //
            .build();
}
 
Example #11
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 #12
Source File: RingBufferLogEventTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Test
public void testMementoReuse() {
    final RingBufferLogEvent evt = new RingBufferLogEvent();
    // Initialize the event with parameters
    evt.swapParameters(new Object[10]);
    final String loggerName = "logger.name";
    final Marker marker = MarkerManager.getMarker("marked man");
    final String fqcn = "f.q.c.n";
    final Level level = Level.TRACE;
    ReusableMessageFactory factory = new ReusableMessageFactory();
    Message message = factory.newMessage("Hello {}!", "World");
    try {
        final Throwable t = new InternalError("not a real error");
        final ContextStack contextStack = new MutableThreadContextStack(Arrays.asList("a", "b"));
        final String threadName = "main";
        final StackTraceElement location = null;
        evt.setValues(null, loggerName, marker, fqcn, level, message, t, (StringMap) evt.getContextData(),
                contextStack, -1, threadName, -1, location, new FixedPreciseClock(12345, 678), new DummyNanoClock(1));
        ((StringMap) evt.getContextData()).putValue("key", "value");

        final Message memento1 = evt.memento();
        final Message memento2 = evt.memento();
        assertThat(memento1, sameInstance(memento2));
    } finally {
        ReusableMessageFactory.release(message);
    }
}
 
Example #13
Source File: PropertiesRewritePolicy.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
/**
 * Rewrites the event.
 * @param source a logging event that may be returned or
 * used to create a new logging event.
 * @return The LogEvent after rewriting.
 */
@Override
public LogEvent rewrite(final LogEvent source) {
    final StringMap newContextData = ContextDataFactory.createContextData(source.getContextData());
    for (final Map.Entry<Property, Boolean> entry : properties.entrySet()) {
        final Property prop = entry.getKey();
        newContextData.putValue(prop.getName(), entry.getValue().booleanValue() ?
            config.getStrSubstitutor().replace(prop.getValue()) : prop.getValue());
    }

    return new Log4jLogEvent.Builder(source).setContextData(newContextData).build();
}
 
Example #14
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 #15
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 #16
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 #17
Source File: ContextDataAsEntryListDeserializer.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Override
public StringMap deserialize(final JsonParser jp, final DeserializationContext ctxt)
        throws IOException, JsonProcessingException {
    final List<MapEntry> list = jp.readValueAs(new TypeReference<List<MapEntry>>() {
        // do nothing
    });
    final StringMap contextData = ContextDataFactory.createContextData();
    for (final MapEntry mapEntry : list) {
        contextData.putValue(mapEntry.getKey(), mapEntry.getValue());
    }
    return contextData;
}
 
Example #18
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 #19
Source File: RingBufferLogEventTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Test
public void testCreateMementoRetainsParametersAndFormat() {
    final RingBufferLogEvent evt = new RingBufferLogEvent();
    // Initialize the event with parameters
    evt.swapParameters(new Object[10]);
    final String loggerName = "logger.name";
    final Marker marker = MarkerManager.getMarker("marked man");
    final String fqcn = "f.q.c.n";
    final Level level = Level.TRACE;
    ReusableMessageFactory factory = new ReusableMessageFactory();
    Message message = factory.newMessage("Hello {}!", "World");
    try {
        final Throwable t = new InternalError("not a real error");
        final ContextStack contextStack = new MutableThreadContextStack(Arrays.asList("a", "b"));
        final String threadName = "main";
        final StackTraceElement location = null;
        evt.setValues(null, loggerName, marker, fqcn, level, message, t, (StringMap) evt.getContextData(),
                contextStack, -1, threadName, -1, location, new FixedPreciseClock(12345, 678), new DummyNanoClock(1));
        ((StringMap) evt.getContextData()).putValue("key", "value");

        final Message actual = evt.createMemento().getMessage();
        assertEquals("Hello {}!", actual.getFormat());
        assertArrayEquals(new String[]{"World"}, actual.getParameters());
        assertEquals("Hello World!", actual.getFormattedMessage());
    } finally {
        ReusableMessageFactory.release(message);
    }
}
 
Example #20
Source File: AsyncLogger.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
private static StringMap getContextData(final RingBufferLogEvent event) {
    StringMap contextData = (StringMap) event.getContextData();
    if (contextData.isFrozen()) {
        final StringMap temp = ContextDataFactory.createContextData();
        temp.putAll(contextData);
        return temp;
    }
    return contextData;
}
 
Example #21
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 #22
Source File: CopyOnWriteSortedArrayThreadContextMap.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Override
public int hashCode() {
    final int prime = 31;
    int result = 1;
    final StringMap map = this.localMap.get();
    result = prime * result + ((map == null) ? 0 : map.hashCode());
    return result;
}
 
Example #23
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 #24
Source File: RingBufferLogEventTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Test
public void testSerializationDeserialization() throws IOException, ClassNotFoundException {
    final RingBufferLogEvent evt = new RingBufferLogEvent();
    final String loggerName = "logger.name";
    final Marker marker = null;
    final String fqcn = "f.q.c.n";
    final Level level = Level.TRACE;
    final Message data = new SimpleMessage("message");
    final Throwable t = new InternalError("not a real error");
    final ContextStack contextStack = null;
    final String threadName = "main";
    final StackTraceElement location = null;
    evt.setValues(null, loggerName, marker, fqcn, level, data, t, (StringMap) evt.getContextData(),
            contextStack, -1, threadName, -1, location,
            new FixedPreciseClock(12345, 678), new DummyNanoClock(1));
    ((StringMap) evt.getContextData()).putValue("key", "value");

    final ByteArrayOutputStream baos = new ByteArrayOutputStream();
    final ObjectOutputStream out = new ObjectOutputStream(baos);
    out.writeObject(evt);

    final ObjectInputStream in = new FilteredObjectInputStream(new ByteArrayInputStream(baos.toByteArray()));
    final RingBufferLogEvent other = (RingBufferLogEvent) in.readObject();
    assertEquals(loggerName, other.getLoggerName());
    assertEquals(marker, other.getMarker());
    assertEquals(fqcn, other.getLoggerFqcn());
    assertEquals(level, other.getLevel());
    assertEquals(data, other.getMessage());
    assertNull("null after serialization", other.getThrown());
    assertEquals(new ThrowableProxy(t), other.getThrownProxy());
    assertEquals(evt.getContextData(), other.getContextData());
    assertEquals(contextStack, other.getContextStack());
    assertEquals(threadName, other.getThreadName());
    assertEquals(location, other.getSource());
    assertEquals(12345, other.getTimeMillis());
    assertEquals(678, other.getInstant().getNanoOfMillisecond());
}
 
Example #25
Source File: RingBufferLogEventTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("deprecation")
@Test
public void testCreateMementoReturnsCopy() {
    final RingBufferLogEvent evt = new RingBufferLogEvent();
    final String loggerName = "logger.name";
    final Marker marker = MarkerManager.getMarker("marked man");
    final String fqcn = "f.q.c.n";
    final Level level = Level.TRACE;
    final Message data = new SimpleMessage("message");
    final Throwable t = new InternalError("not a real error");
    final ContextStack contextStack = new MutableThreadContextStack(Arrays.asList("a", "b"));
    final String threadName = "main";
    final StackTraceElement location = null;
    evt.setValues(null, loggerName, marker, fqcn, level, data, t, (StringMap) evt.getContextData(),
            contextStack, -1, threadName, -1, location, new FixedPreciseClock(12345, 678), new DummyNanoClock(1));
    ((StringMap) evt.getContextData()).putValue("key", "value");

    final LogEvent actual = evt.createMemento();
    assertEquals(evt.getLoggerName(), actual.getLoggerName());
    assertEquals(evt.getMarker(), actual.getMarker());
    assertEquals(evt.getLoggerFqcn(), actual.getLoggerFqcn());
    assertEquals(evt.getLevel(), actual.getLevel());
    assertEquals(evt.getMessage(), actual.getMessage());
    assertEquals(evt.getThrown(), actual.getThrown());
    assertEquals(evt.getContextData(), actual.getContextData());
    assertEquals(evt.getContextStack(), actual.getContextStack());
    assertEquals(evt.getThreadName(), actual.getThreadName());
    assertEquals(evt.getTimeMillis(), actual.getTimeMillis());
    assertEquals(evt.getInstant().getNanoOfMillisecond(), actual.getInstant().getNanoOfMillisecond());
    assertEquals(evt.getSource(), actual.getSource());
    assertEquals(evt.getThrownProxy(), actual.getThrownProxy());
}
 
Example #26
Source File: CopyOnWriteSortedArrayThreadContextMap.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Override
public <V> void putAllValues(final Map<String, V> values) {
    if (values == null || values.isEmpty()) {
        return;
    }
    StringMap map = localMap.get();
    map = map == null ? createStringMap() : createStringMap(map);
    for (final Map.Entry<String, V> entry : values.entrySet()) {
        map.putValue(entry.getKey(), entry.getValue());
    }
    map.freeze();
    localMap.set(map);
}
 
Example #27
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 #28
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 #29
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 #30
Source File: RequestLoggingContextInjector.java    From curiostack with MIT License 5 votes vote down vote up
@Override
public StringMap injectContextData(List<Property> properties, StringMap reusable) {
  ImmutableMap<String, String> current = RequestLoggingContext.get();
  if (properties == null || properties.isEmpty()) {
    return new JdkMapAdapaterStringMap(current);
  }
  ImmutableMap.Builder<String, String> injected =
      ImmutableMap.builderWithExpectedSize(current.size() + properties.size());
  injected.putAll(current);
  for (Property prop : properties) {
    // This will throw if a property name is already in the context, don't worry about it for now.
    injected.put(prop.getName(), prop.getValue());
  }
  return new JdkMapAdapaterStringMap(injected.build());
}