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

The following examples show how to use org.apache.logging.log4j.util.StringMap. These examples are extracted from open source projects. 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
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 2
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 3
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 4
Source Project: logging-log4j2   Source File: Log4jLogEvent.java    License: 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 5
Source Project: logging-log4j2   Source File: GelfLayoutBenchmark.java    License: 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 6
Source Project: logging-log4j2   Source File: TextEncoderHelperBenchmark.java    License: 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 7
Source Project: logging-log4j2   Source File: ThreadContextDataInjector.java    License: 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 8
Source Project: logging-log4j2   Source File: RingBufferLogEventTest.java    License: 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 9
Source Project: logging-log4j2   Source File: ContextDataDeserializer.java    License: 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 10
@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 11
Source Project: curiostack   Source File: RequestLoggingContextInjector.java    License: 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());
}
 
Example 12
Source Project: logging-log4j2   Source File: PatternParserTest.java    License: 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 13
Source Project: logging-log4j2   Source File: ContextDataFactory.java    License: 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 14
private static void assertContainsOnlyDefaultTracingEntries(StringMap stringMap) {
  assertThat(stringMap.toMap())
      .containsExactly(
          "traceId",
          "00000000000000000000000000000000",
          "spanId",
          "0000000000000000",
          "traceSampled",
          "false");
}
 
Example 15
Source Project: samza   Source File: StreamAppender.java    License: Apache License 2.0 5 votes vote down vote up
private LogEvent subLog(LogEvent event) {
  return Log4jLogEvent.newBuilder()
      .setLevel(event.getLevel())
      .setLoggerName(event.getLoggerName())
      .setLoggerFqcn(event.getLoggerFqcn())
      .setMessage(subAppend(event))
      .setThrown(event.getThrown())
      .setContextData((StringMap) event.getContextData())
      .setContextStack(event.getContextStack())
      .setThreadName(event.getThreadName())
      .setSource(event.getSource())
      .setTimeMillis(event.getTimeMillis())
      .build();
}
 
Example 16
Source Project: logging-log4j2   Source File: ContextDataFactory.java    License: Apache License 2.0 5 votes vote down vote up
private static Class<? extends StringMap> createCachedClass(final String className) {
    if (className == null) {
        return null;
    }
    try {
        return Loader.loadClass(className).asSubclass(IndexedStringMap.class);
    } catch (final Exception any) {
        return null;
    }
}
 
Example 17
Source Project: logging-log4j2   Source File: AsyncLogger.java    License: Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("ForLoopReplaceableByForEach") // Avoid iterator allocation
private void onPropertiesPresent(final RingBufferLogEvent event, final List<Property> properties) {
    StringMap contextData = getContextData(event);
    for (int i = 0, size = properties.size(); i < size; i++) {
        final Property prop = properties.get(i);
        if (contextData.getValue(prop.getName()) != null) {
            continue; // contextMap overrides config properties
        }
        final String value = prop.isValueNeedsLookup() //
                ? privateConfig.config.getStrSubstitutor().replace(event, prop.getValue()) //
                : prop.getValue();
        contextData.putValue(prop.getName(), value);
    }
    event.setContextData(contextData);
}
 
Example 18
Source Project: logging-log4j2   Source File: ThreadContextDataInjector.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Puts key-value pairs from both the specified list of properties as well as the thread context into the
 * specified reusable StringMap.
 *
 * @param props list of configuration properties, may be {@code null}
 * @param contextData 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 contextData) {

    final Map<String, String> copy;

    if (providers.size() == 1) {
        copy = providers.get(0).supplyContextData();
    } else {
        copy = new HashMap<>();
        for (ContextDataProvider provider : providers) {
            copy.putAll(provider.supplyContextData());
        }
    }

    // The DefaultThreadContextMap stores context data in a Map<String, String>.
    // This is a copy-on-write data structure so we are sure ThreadContext changes will not affect our copy.
    // If there are no configuration properties or providers returning a thin wrapper around the copy
    // is faster than copying the elements into the LogEvent's reusable StringMap.
    if ((props == null || props.isEmpty())) {
        // this will replace the LogEvent's context data with the returned instance.
        // NOTE: must mark as frozen or downstream components may attempt to modify (UnsupportedOperationEx)
        return copy.isEmpty() ? ContextDataFactory.emptyFrozenContextData() : frozenStringMap(copy);
    }
    // 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 = new JdkMapAdapterStringMap(new HashMap<>(copy));
    for (int i = 0; i < props.size(); i++) {
        final Property prop = props.get(i);
        if (!copy.containsKey(prop.getName())) {
            result.putValue(prop.getName(), prop.getValue());
        }
    }
    result.freeze();
    return result;
}
 
Example 19
@Override
public void translateTo(final RingBufferLogEvent event, final long sequence) {

    event.setValues(asyncLogger, loggerName, marker, fqcn, level, message, thrown,
            // config properties are taken care of in the EventHandler thread
            // in the AsyncLogger#actualAsyncLog method
            injector.injectContextData(null, (StringMap) event.getContextData()), contextStack,
            threadId, threadName, threadPriority, location, clock, nanoClock);

    clear(); // clear the translator
}
 
Example 20
private ThreadLocal<StringMap> createThreadLocalMap() {
    if (inheritableMap) {
        return new InheritableThreadLocal<StringMap>() {
            @Override
            protected StringMap childValue(final StringMap parentValue) {
                return parentValue != null ? createStringMap(parentValue) : null;
            }
        };
    }
    // if not inheritable, return plain ThreadLocal with null as initial value
    return new ThreadLocal<>();
}
 
Example 21
Source Project: logging-log4j2   Source File: ContextDataFactory.java    License: Apache License 2.0 5 votes vote down vote up
private static Constructor<?> createInitialCapacityConstructor(final Class<? extends StringMap> cachedClass){
    if (cachedClass == null) {
        return null;
    }
    try {
        return cachedClass.getConstructor(int.class);
    } catch (final NoSuchMethodException | IllegalAccessError ignored) {
        return null;
    }
}
 
Example 22
private StringMap getThreadLocalMap() {
    StringMap map = localMap.get();
    if (map == null) {
        map = createStringMap();
        localMap.set(map);
    }
    return map;
}
 
Example 23
@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 24
@Override
public <V> void putAllValues(final Map<String, V> values) {
    if (values == null || values.isEmpty()) {
        return;
    }
    final StringMap map = getThreadLocalMap();
    for (final Map.Entry<String, V> entry : values.entrySet()) {
        map.putValue(entry.getKey(), entry.getValue());
    }
}
 
Example 25
@Override
public void remove(final String key) {
    final StringMap map = localMap.get();
    if (map != null) {
        map.remove(key);
    }
}
 
Example 26
@Override
public void removeAll(final Iterable<String> keys) {
    final StringMap map = localMap.get();
    if (map != null) {
        for (final String key : keys) {
            map.remove(key);
        }
    }
}
 
Example 27
@Override
public void clear() {
    final StringMap map = localMap.get();
    if (map != null) {
        map.clear();
    }
}
 
Example 28
Source Project: logging-log4j2   Source File: AsyncLogger.java    License: 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 29
Source Project: logging-log4j2   Source File: Log4jLogEvent.java    License: 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
@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);
}