Java Code Examples for org.apache.logging.log4j.util.ReadOnlyStringMap#forEach()

The following examples show how to use org.apache.logging.log4j.util.ReadOnlyStringMap#forEach() . 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: 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 2
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 3
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 4
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 5
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 6
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 7
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 8
Source File: Log4j1XmlLayout.java    From logging-log4j2 with Apache License 2.0 4 votes vote down vote up
private void formatTo(final LogEvent event, final StringBuilder buf) {
      // We yield to the \r\n heresy.

      buf.append("<log4j:event logger=\"");
      buf.append(Transform.escapeHtmlTags(event.getLoggerName()));
      buf.append("\" timestamp=\"");
      buf.append(event.getTimeMillis());
      buf.append("\" level=\"");
      buf.append(Transform.escapeHtmlTags(String.valueOf(event.getLevel())));
      buf.append("\" thread=\"");
      buf.append(Transform.escapeHtmlTags(event.getThreadName()));
      buf.append("\">\r\n");

      buf.append("<log4j:message><![CDATA[");
      // Append the rendered message. Also make sure to escape any existing CDATA sections.
      Transform.appendEscapingCData(buf, event.getMessage().getFormattedMessage());
      buf.append("]]></log4j:message>\r\n");

      final List<String> ndc = event.getContextStack().asList();
      if (!ndc.isEmpty()) {
          buf.append("<log4j:NDC><![CDATA[");
          Transform.appendEscapingCData(buf, Strings.join(ndc, ' '));
          buf.append("]]></log4j:NDC>\r\n");
      }

      @SuppressWarnings("ThrowableResultOfMethodCallIgnored")
final Throwable thrown = event.getThrown();
      if (thrown != null) {
          buf.append("<log4j:throwable><![CDATA[");
          final StringWriter w = new StringWriter();
          thrown.printStackTrace(new PrintWriter(w));
          Transform.appendEscapingCData(buf, w.toString());
          buf.append("]]></log4j:throwable>\r\n");
      }

      if (locationInfo) {
          final StackTraceElement source = event.getSource();
          if (source != null) {
              buf.append("<log4j:locationInfo class=\"");
              buf.append(Transform.escapeHtmlTags(source.getClassName()));
              buf.append("\" method=\"");
              buf.append(Transform.escapeHtmlTags(source.getMethodName()));
              buf.append("\" file=\"");
              buf.append(Transform.escapeHtmlTags(source.getFileName()));
              buf.append("\" line=\"");
              buf.append(source.getLineNumber());
              buf.append("\"/>\r\n");
          }
      }

      if (properties) {
          final ReadOnlyStringMap contextMap = event.getContextData();
          if (!contextMap.isEmpty()) {
              buf.append("<log4j:properties>\r\n");
              contextMap.forEach(new BiConsumer<String, String>() {
                  @Override
                  public void accept(final String key, final String val) {
                      if (val != null) {
                          buf.append("<log4j:data name=\"");
                          buf.append(Transform.escapeHtmlTags(key));
                          buf.append("\" value=\"");
                          buf.append(Transform.escapeHtmlTags(val));
                          buf.append("\"/>\r\n");
                      }
                  }
              });
              buf.append("</log4j:properties>\r\n");
          }
      }

      buf.append("</log4j:event>\r\n\r\n");
  }
 
Example 9
Source File: Log4j1XmlLayout.java    From logging-log4j2 with Apache License 2.0 4 votes vote down vote up
private void formatTo(final LogEvent event, final StringBuilder buf) {
      // We yield to the \r\n heresy.

      buf.append("<log4j:event logger=\"");
      buf.append(Transform.escapeHtmlTags(event.getLoggerName()));
      buf.append("\" timestamp=\"");
      buf.append(event.getTimeMillis());
      buf.append("\" level=\"");
      buf.append(Transform.escapeHtmlTags(String.valueOf(event.getLevel())));
      buf.append("\" thread=\"");
      buf.append(Transform.escapeHtmlTags(event.getThreadName()));
      buf.append("\">\r\n");

      buf.append("<log4j:message><![CDATA[");
      // Append the rendered message. Also make sure to escape any existing CDATA sections.
      Transform.appendEscapingCData(buf, event.getMessage().getFormattedMessage());
      buf.append("]]></log4j:message>\r\n");

      final List<String> ndc = event.getContextStack().asList();
      if (!ndc.isEmpty()) {
          buf.append("<log4j:NDC><![CDATA[");
          Transform.appendEscapingCData(buf, Strings.join(ndc, ' '));
          buf.append("]]></log4j:NDC>\r\n");
      }

      @SuppressWarnings("ThrowableResultOfMethodCallIgnored")
final Throwable thrown = event.getThrown();
      if (thrown != null) {
          buf.append("<log4j:throwable><![CDATA[");
          final StringWriter w = new StringWriter();
          thrown.printStackTrace(new PrintWriter(w));
          Transform.appendEscapingCData(buf, w.toString());
          buf.append("]]></log4j:throwable>\r\n");
      }

      if (locationInfo) {
          final StackTraceElement source = event.getSource();
          if (source != null) {
              buf.append("<log4j:locationInfo class=\"");
              buf.append(Transform.escapeHtmlTags(source.getClassName()));
              buf.append("\" method=\"");
              buf.append(Transform.escapeHtmlTags(source.getMethodName()));
              buf.append("\" file=\"");
              buf.append(Transform.escapeHtmlTags(source.getFileName()));
              buf.append("\" line=\"");
              buf.append(source.getLineNumber());
              buf.append("\"/>\r\n");
          }
      }

      if (properties) {
          final ReadOnlyStringMap contextMap = event.getContextData();
          if (!contextMap.isEmpty()) {
              buf.append("<log4j:properties>\r\n");
              contextMap.forEach(new BiConsumer<String, String>() {
                  @Override
                  public void accept(final String key, final String val) {
                      if (val != null) {
                          buf.append("<log4j:data name=\"");
                          buf.append(Transform.escapeHtmlTags(key));
                          buf.append("\" value=\"");
                          buf.append(Transform.escapeHtmlTags(val));
                          buf.append("\"/>\r\n");
                      }
                  }
              });
              buf.append("</log4j:properties>\r\n");
          }
      }

      buf.append("</log4j:event>\r\n\r\n");
  }
 
Example 10
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 11
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());
    }
}