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

The following examples show how to use org.apache.logging.log4j.util.ReadOnlyStringMap. 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: ThreadContextMapFilter.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
private Result filter() {
    boolean match = false;
    if (useMap) {
        ReadOnlyStringMap currentContextData = null;
        final IndexedReadOnlyStringMap map = getStringMap();
        for (int i = 0; i < map.size(); i++) {
            if (currentContextData == null) {
                currentContextData = currentContextData();
            }
            final String toMatch = currentContextData.getValue(map.getKeyAt(i));
            match = toMatch != null && ((List<String>) map.getValueAt(i)).contains(toMatch);
            if ((!isAnd() && match) || (isAnd() && !match)) {
                break;
            }
        }
    } else {
        match = value.equals(currentContextData().getValue(key));
    }
    return match ? onMatch : onMismatch;
}
 
Example #2
Source File: ColumnMapping.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
@Override
public ColumnMapping build() {
    if (pattern != null) {
        layout = PatternLayout.newBuilder()
            .setPattern(pattern)
            .setConfiguration(configuration)
            .setAlwaysWriteExceptions(false)
            .build();
    }
    if (!(layout == null
        || literal == null
        || Date.class.isAssignableFrom(type)
        || ReadOnlyStringMap.class.isAssignableFrom(type)
        || ThreadContextMap.class.isAssignableFrom(type)
        || ThreadContextStack.class.isAssignableFrom(type))) {
        LOGGER.error("No 'layout' or 'literal' value specified and type ({}) is not compatible with ThreadContextMap, ThreadContextStack, or java.util.Date for the mapping", type, this);
        return null;
    }
    if (literal != null && parameter != null) {
        LOGGER.error("Only one of 'literal' or 'parameter' can be set on the column mapping {}", this);
        return null;
    }
    return new ColumnMapping(name, source, layout, literal, parameter, type);
}
 
Example #3
Source File: MdcPatternConverter.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
private static void appendSelectedKeys(final String[] keys, final ReadOnlyStringMap contextData, final StringBuilder sb) {
    // Print all the keys in the array that have a value.
    final int start = sb.length();
    sb.append('{');
    for (int i = 0; i < keys.length; i++) {
        final String theKey = keys[i];
        final Object value = contextData.getValue(theKey);
        if (value != null) { // !contextData.containskey(theKey)
            if (sb.length() - start > 1) {
                sb.append(", ");
            }
            sb.append(theKey).append('=');
            StringBuilders.appendValue(sb, value);
        }
    }
    sb.append('}');
}
 
Example #4
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 #5
Source File: ContextDataJsonAttributeConverter.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
@Override
public String convertToDatabaseColumn(final ReadOnlyStringMap contextData) {
    if (contextData == null) {
        return null;
    }

    try {
        final JsonNodeFactory factory = OBJECT_MAPPER.getNodeFactory();
        final ObjectNode root = factory.objectNode();
        contextData.forEach(new BiConsumer<String, Object>() {
            @Override
            public void accept(final String key, final Object value) {
                // we will cheat here and write the toString of the Object... meh, but ok.
                root.put(key, String.valueOf(value));
            }
        });
        return OBJECT_MAPPER.writeValueAsString(root);
    } catch (final Exception e) {
        throw new PersistenceException("Failed to convert contextData to JSON string.", e);
    }
}
 
Example #6
Source File: CassandraManager.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
@Override
protected void writeInternal(final LogEvent event, final Serializable serializable) {
    for (int i = 0; i < columnMappings.size(); i++) {
        final ColumnMapping columnMapping = columnMappings.get(i);
        if (ThreadContextMap.class.isAssignableFrom(columnMapping.getType())
            || ReadOnlyStringMap.class.isAssignableFrom(columnMapping.getType())) {
            values[i] = event.getContextData().toMap();
        } else if (ThreadContextStack.class.isAssignableFrom(columnMapping.getType())) {
            values[i] = event.getContextStack().asList();
        } else if (Date.class.isAssignableFrom(columnMapping.getType())) {
            values[i] = DateTypeConverter.fromMillis(event.getTimeMillis(), columnMapping.getType().asSubclass(Date.class));
        } else {
            values[i] = TypeConverters.convert(columnMapping.getLayout().toSerializable(event),
                columnMapping.getType(), null);
        }
    }
    final BoundStatement boundStatement = preparedStatement.bind(values);
    if (batchStatement == null) {
        session.execute(boundStatement);
    } else {
        batchStatement.add(boundStatement);
    }
}
 
Example #7
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 #8
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 #9
Source File: ContextDataSerializer.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Override
public void serialize(final ReadOnlyStringMap contextData, final JsonGenerator jgen,
        final SerializerProvider provider) throws IOException, JsonGenerationException {

    jgen.writeStartObject();
    contextData.forEach(WRITE_STRING_FIELD_INTO, jgen);
    jgen.writeEndObject();
}
 
Example #10
Source File: ContextDataAsEntryListSerializer.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Override
public void serialize(final ReadOnlyStringMap contextData, final JsonGenerator jgen,
        final SerializerProvider provider) throws IOException, JsonGenerationException {

    final MapEntry[] pairs = createMapEntryArray(contextData.size());
    contextData.forEach(new BiConsumer<String, Object>() {
        int i = 0;

        @Override
        public void accept(final String key, final Object value) {
            pairs[i++] = createMapEntry(key, String.valueOf(value));
        }
    });
    jgen.writeObject(pairs);
}
 
Example #11
Source File: ThreadContextDataInjector.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Override
public ReadOnlyStringMap rawContextData() {
    final ReadOnlyThreadContextMap map = ThreadContext.getThreadContextMap();
    if (map instanceof ReadOnlyStringMap) {
        return (ReadOnlyStringMap) map;
    }
    // note: default ThreadContextMap is null
    final Map<String, String> copy = ThreadContext.getImmutableContext();
    return copy.isEmpty() ? ContextDataFactory.emptyFrozenContextData() : new JdkMapAdapterStringMap(copy);
}
 
Example #12
Source File: ContextDataAttributeConverter.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Override
public String convertToDatabaseColumn(final ReadOnlyStringMap contextData) {
    if (contextData == null) {
        return null;
    }

    return contextData.toString();
}
 
Example #13
Source File: MdcPatternConverter.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
private static void appendFully(final ReadOnlyStringMap contextData, final StringBuilder toAppendTo) {
    toAppendTo.append("{");
    final int start = toAppendTo.length();
    contextData.forEach(WRITE_KEY_VALUES_INTO, toAppendTo);
    final int end = toAppendTo.length();
    if (end > start) {
        toAppendTo.setCharAt(end - 2, '}');
        toAppendTo.deleteCharAt(end - 1);
    } else {
        toAppendTo.append('}');
    }
}
 
Example #14
Source File: CustomFieldsConverter.java    From cf-java-logging-support with Apache License 2.0 5 votes vote down vote up
private Map<String, String> getCustomFieldsFromMdc(LogEvent event) {
	ReadOnlyStringMap contextData = event.getContextData();
	if (contextData == null || contextData.isEmpty()) {
		return Collections.emptyMap();
	}
	CustomFieldsMdcCollector mdcCollector = new CustomFieldsMdcCollector();
	contextData.forEach(mdcCollector);
	return mdcCollector.getCustomFields();
}
 
Example #15
Source File: MdcPatternConverter.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void format(final LogEvent event, final StringBuilder toAppendTo) {
    final ReadOnlyStringMap contextData = event.getContextData();
    // if there is no additional options, we output every single
    // Key/Value pair for the MDC in a similar format to Hashtable.toString()
    if (full) {
        if (contextData == null || contextData.size() == 0) {
            toAppendTo.append("{}");
            return;
        }
        appendFully(contextData, toAppendTo);
    } else {
        if (keys != null) {
            if (contextData == null || contextData.size() == 0) {
                toAppendTo.append("{}");
                return;
            }
            appendSelectedKeys(keys, contextData, toAppendTo);
        } else if (contextData != null){
            // otherwise they just want a single key output
            final Object value = contextData.getValue(key);
            if (value != null) {
                StringBuilders.appendValue(toAppendTo, value);
            }
        }
    }
}
 
Example #16
Source File: OpenHashStringMap.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Override
public void putAll(final ReadOnlyStringMap source) {
    assertNotFrozen();
    assertNoConcurrentModification();

    if (size() == 0 && source instanceof OpenHashStringMap) {
        initFrom0((OpenHashStringMap) source);
    } else if (source != null) {
        source.forEach(PUT_ALL, this);
    }
}
 
Example #17
Source File: OpenHashStringMap.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Override
public boolean equals(final Object obj) {
       if (obj == this) {
           return true;
       }
       if (!(obj instanceof ReadOnlyStringMap)) {
           return false;
       }
       final ReadOnlyStringMap other = (ReadOnlyStringMap) obj;
       if (other.size() != size()) {
           return false;
       }
       int pos = arraySize;
       if (containsNullKey) {
           if (!Objects.equals(getObjectValue(null), other.getValue(null))) {
               return false;
           }
       }
       --pos;
       final K myKeys[] = this.keys;
       for (; pos >= 0; pos--) {
           K k;
           if ((k = myKeys[pos]) != null) {
               if (!Objects.equals(values[pos], other.getValue((String) k))) {
                   return false;
               }
           }
       }
       return true;
   }
 
Example #18
Source File: OpenHashStringMap.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new hash map copying a given type-specific one.
 *
 * @param contextData
 *            a type-specific map to be copied into the new hash map.
 * @param f
 *            the load factor.
 */
public OpenHashStringMap(final ReadOnlyStringMap contextData, final float f) {
    this(contextData.size(), f);
    if (contextData instanceof OpenHashStringMap) {
        initFrom0((OpenHashStringMap) contextData);
    } else {
        contextData.forEach(PUT_ALL, this);
    }
}
 
Example #19
Source File: LogSearchJsonLayout.java    From ambari-logsearch with Apache License 2.0 5 votes vote down vote up
public LogSearchJsonLayout(Charset charset) {
  super(charset);
  SimpleModule module = new SimpleModule();
  module.addSerializer(LogEvent.class, new LogEventSerializer());
  module.addSerializer(ReadOnlyStringMap.class, new ContextDataSerializer() {
  });
  objectMapper = new ObjectMapper();
  objectMapper.registerModule(module);
  objectMapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
}
 
Example #20
Source File: DynamicThresholdFilter.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
private Result filter(final Level level, final ReadOnlyStringMap contextMap) {
    final String value = contextMap.getValue(key);
    if (value != null) {
        Level ctxLevel = levelMap.get(value);
        if (ctxLevel == null) {
            ctxLevel = defaultThreshold;
        }
        return level.isMoreSpecificThan(ctxLevel) ? onMatch : onMismatch;
    }
    return Result.NEUTRAL;

}
 
Example #21
Source File: MapFilter.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
protected boolean filter(final ReadOnlyStringMap data) {
    boolean match = false;
    for (int i = 0; i < map.size(); i++) {
        final String toMatch = data.getValue(map.getKeyAt(i));
        match = toMatch != null && ((List<String>) map.getValueAt(i)).contains(toMatch);

        if ((!isAnd && match) || (isAnd && !match)) {
            break;
        }
    }
    return match;
}
 
Example #22
Source File: TestLogEventMixIn.java    From log4j2-elasticsearch with Apache License 2.0 4 votes vote down vote up
@JsonIgnore
@Override
public abstract ReadOnlyStringMap getContextData();
 
Example #23
Source File: AbstractLogEvent.java    From logging-log4j2 with Apache License 2.0 4 votes vote down vote up
@Override
public ReadOnlyStringMap getContextData() {
    return null;
}
 
Example #24
Source File: LogEventWithContextListXmlMixIn.java    From logging-log4j2 with Apache License 2.0 4 votes vote down vote up
@JacksonXmlProperty(namespace = XmlConstants.XML_NAMESPACE, localName = XmlConstants.ELT_CONTEXT_MAP)
@JsonSerialize(using = ContextDataAsEntryListXmlSerializer.class)
@JsonDeserialize(using = ContextDataAsEntryListDeserializer.class)
@Override
public abstract ReadOnlyStringMap getContextData();
 
Example #25
Source File: ContextMapLookup.java    From logging-log4j2 with Apache License 2.0 4 votes vote down vote up
private ReadOnlyStringMap currentContextData() {
    return injector.rawContextData();
}
 
Example #26
Source File: MutableLogEvent.java    From logging-log4j2 with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public ReadOnlyStringMap getContextData() {
    return contextData;
}
 
Example #27
Source File: RequestLoggingContextInjector.java    From curiostack with MIT License 4 votes vote down vote up
@Override
public void putAll(ReadOnlyStringMap source) {
  throw new UnsupportedOperationException();
}
 
Example #28
Source File: JdkMapAdapterStringMap.java    From logging-log4j2 with Apache License 2.0 4 votes vote down vote up
@Override
public void putAll(final ReadOnlyStringMap source) {
    assertNotFrozen();
    source.forEach(PUT_ALL, map);
    sortedKeys = null;
}
 
Example #29
Source File: NoSqlDatabaseManager.java    From logging-log4j2 with Apache License 2.0 4 votes vote down vote up
private void setFields(final LogEvent event, final NoSqlObject<W> entity) {
    entity.set("level", event.getLevel());
    entity.set("loggerName", event.getLoggerName());
    entity.set("message", event.getMessage() == null ? null : event.getMessage().getFormattedMessage());

    final StackTraceElement source = event.getSource();
    if (source == null) {
        entity.set("source", (Object) null);
    } else {
        entity.set("source", this.convertStackTraceElement(source));
    }

    final Marker marker = event.getMarker();
    if (marker == null) {
        entity.set("marker", (Object) null);
    } else {
        entity.set("marker", buildMarkerEntity(marker));
    }

    entity.set("threadId", event.getThreadId());
    entity.set("threadName", event.getThreadName());
    entity.set("threadPriority", event.getThreadPriority());
    entity.set("millis", event.getTimeMillis());
    entity.set("date", new java.util.Date(event.getTimeMillis()));

    @SuppressWarnings("ThrowableResultOfMethodCallIgnored")
    Throwable thrown = event.getThrown();
    if (thrown == null) {
        entity.set("thrown", (Object) null);
    } else {
        final NoSqlObject<W> originalExceptionEntity = this.connection.createObject();
        NoSqlObject<W> exceptionEntity = originalExceptionEntity;
        exceptionEntity.set("type", thrown.getClass().getName());
        exceptionEntity.set("message", thrown.getMessage());
        exceptionEntity.set("stackTrace", this.convertStackTrace(thrown.getStackTrace()));
        while (thrown.getCause() != null) {
            thrown = thrown.getCause();
            final NoSqlObject<W> causingExceptionEntity = this.connection.createObject();
            causingExceptionEntity.set("type", thrown.getClass().getName());
            causingExceptionEntity.set("message", thrown.getMessage());
            causingExceptionEntity.set("stackTrace", this.convertStackTrace(thrown.getStackTrace()));
            exceptionEntity.set("cause", causingExceptionEntity);
            exceptionEntity = causingExceptionEntity;
        }

        entity.set("thrown", originalExceptionEntity);
    }

    final ReadOnlyStringMap contextMap = event.getContextData();
    if (contextMap == null) {
        entity.set("contextMap", (Object) null);
    } else {
        final NoSqlObject<W> contextMapEntity = this.connection.createObject();
        contextMap.forEach(new BiConsumer<String, String>() {
            @Override
            public void accept(final String key, final String val) {
                contextMapEntity.set(key, val);
            }
        });
        entity.set("contextMap", contextMapEntity);
    }

    final ThreadContext.ContextStack contextStack = event.getContextStack();
    if (contextStack == null) {
        entity.set("contextStack", (Object) null);
    } else {
        entity.set("contextStack", contextStack.asList().toArray());
    }
}
 
Example #30
Source File: ThreadContextDataInjector.java    From logging-log4j2 with Apache License 2.0 4 votes vote down vote up
@Override
public ReadOnlyStringMap rawContextData() {
    return ThreadContext.getThreadContextMap().getReadOnlyContextData();
}