org.apache.logging.log4j.core.pattern.PatternFormatter Java Examples

The following examples show how to use org.apache.logging.log4j.core.pattern.PatternFormatter. 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: Rfc5424Layout.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
private void appendMessage(final StringBuilder buffer, final LogEvent event) {
    final Message message = event.getMessage();
    // This layout formats StructuredDataMessages instead of delegating to the Message itself.
    final String text = (message instanceof StructuredDataMessage || message instanceof MessageCollectionMessage)
            ? message.getFormat() : message.getFormattedMessage();

    if (text != null && text.length() > 0) {
        buffer.append(' ').append(escapeNewlines(text, escapeNewLine));
    }

    if (exceptionFormatters != null && event.getThrown() != null) {
        final StringBuilder exception = new StringBuilder(LF);
        for (final PatternFormatter formatter : exceptionFormatters) {
            formatter.format(event, exception);
        }
        buffer.append(escapeNewlines(exception.toString(), escapeNewLine));
    }
    if (includeNewLine) {
        buffer.append(LF);
    }
}
 
Example #2
Source File: Rfc5424Layout.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
private Map<String, FieldFormatter> createFieldFormatters(final LoggerFields[] loggerFields,
        final Configuration config) {
    final Map<String, FieldFormatter> sdIdMap = new HashMap<>(loggerFields == null ? 0 : loggerFields.length);
    if (loggerFields != null) {
        for (final LoggerFields loggerField : loggerFields) {
            final StructuredDataId key = loggerField.getSdId() == null ? mdcSdId : loggerField.getSdId();
            final Map<String, List<PatternFormatter>> sdParams = new HashMap<>();
            final Map<String, String> fields = loggerField.getMap();
            if (!fields.isEmpty()) {
                final PatternParser fieldParser = createPatternParser(config, null);

                for (final Map.Entry<String, String> entry : fields.entrySet()) {
                    final List<PatternFormatter> formatters = fieldParser.parse(entry.getValue());
                    sdParams.put(entry.getKey(), formatters);
                }
                final FieldFormatter fieldFormatter = new FieldFormatter(sdParams,
                        loggerField.getDiscardIfAllFieldsAreEmpty());
                sdIdMap.put(key.toString(), fieldFormatter);
            }
        }
    }
    return sdIdMap.size() > 0 ? sdIdMap : null;
}
 
Example #3
Source File: MinecraftFormattingConverter.java    From TerminalConsoleAppender with MIT License 6 votes vote down vote up
/**
 * Gets a new instance of the {@link MinecraftFormattingConverter} with the
 * specified options.
 *
 * @param config The current configuration
 * @param options The pattern options
 * @return The new instance
 *
 * @see MinecraftFormattingConverter
 */
public static @Nullable MinecraftFormattingConverter newInstance(Configuration config, String[] options) {
    if (options.length < 1 || options.length > 2) {
        LOGGER.error("Incorrect number of options on minecraftFormatting. Expected at least 1, max 2 received " + options.length);
        return null;
    }
    if (options[0] == null) {
        LOGGER.error("No pattern supplied on minecraftFormatting");
        return null;
    }

    PatternParser parser = PatternLayout.createPatternParser(config);
    List<PatternFormatter> formatters = parser.parse(options[0]);
    boolean strip = options.length > 1 && "strip".equals(options[1]);
    return new MinecraftFormattingConverter(formatters, strip);
}
 
Example #4
Source File: PatternLayout.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
@Override
public Serializer build() {
    if (Strings.isEmpty(pattern) && Strings.isEmpty(defaultPattern)) {
        return null;
    }
    if (patternSelector == null) {
        try {
            final PatternParser parser = createPatternParser(configuration);
            final List<PatternFormatter> list = parser.parse(pattern == null ? defaultPattern : pattern,
                    alwaysWriteExceptions, disableAnsi, noConsoleNoAnsi);
            final PatternFormatter[] formatters = list.toArray(new PatternFormatter[0]);
            return new PatternSerializer(formatters, replace);
        } catch (final RuntimeException ex) {
            throw new IllegalArgumentException("Cannot parse pattern '" + pattern + "'", ex);
        }
    }
    return new PatternSelectorSerializer(patternSelector, replace);
}
 
Example #5
Source File: EcsLayout.java    From ecs-logging-java with Apache License 2.0 6 votes vote down vote up
private EcsLayout(Configuration config, String serviceName, String eventDataset, boolean includeMarkers, KeyValuePair[] additionalFields, boolean includeOrigin, boolean stackTraceAsArray) {
    super(config, UTF_8, null, null);
    this.serviceName = serviceName;
    this.eventDataset = eventDataset;
    this.includeMarkers = includeMarkers;
    this.includeOrigin = includeOrigin;
    this.stackTraceAsArray = stackTraceAsArray;
    this.additionalFields = additionalFields;
    fieldValuePatternFormatter = new PatternFormatter[additionalFields.length][];
    for (int i = 0; i < additionalFields.length; i++) {
        KeyValuePair additionalField = additionalFields[i];
        if (additionalField.getValue().contains("%")) {
            fieldValuePatternFormatter[i] = PatternLayout.createPatternParser(config)
                    .parse(additionalField.getValue())
                    .toArray(new PatternFormatter[0]);
        }
    }
}
 
Example #6
Source File: IbisPatternLayout.java    From iaf with Apache License 2.0 5 votes vote down vote up
@Override
public StringBuilder toSerializable(final LogEvent event, final StringBuilder buffer) {
	final int len = formatters.length;
	for (int i = 0; i < len; i++) {
		PatternFormatter formatter = formatters[i];
		formatter.format(event, buffer);
	}
	return buffer;
}
 
Example #7
Source File: Rfc5424Layout.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
public StructuredDataElement format(final LogEvent event) {
    final Map<String, String> map = new HashMap<>(delegateMap.size());

    for (final Map.Entry<String, List<PatternFormatter>> entry : delegateMap.entrySet()) {
        final StringBuilder buffer = new StringBuilder();
        for (final PatternFormatter formatter : entry.getValue()) {
            formatter.format(event, buffer);
        }
        map.put(entry.getKey(), buffer.toString());
    }
    return new StructuredDataElement(map, eventPrefix, discardIfEmpty);
}
 
Example #8
Source File: LevelPatternSelector.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Override
public PatternFormatter[] getFormatters(final LogEvent event) {
    final Level level = event.getLevel();
    if (level == null) {
        return defaultFormatters;
    }
    for (final String key : formatterMap.keySet()) {
        if (level.name().equalsIgnoreCase(key)) {
            return formatterMap.get(key);
        }
    }
    return defaultFormatters;
}
 
Example #9
Source File: ScriptPatternSelector.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Override
public PatternFormatter[] getFormatters(final LogEvent event) {
    final SimpleBindings bindings = new SimpleBindings();
    bindings.putAll(configuration.getProperties());
    bindings.put("substitutor", configuration.getStrSubstitutor());
    bindings.put("logEvent", event);
    final Object object = configuration.getScriptManager().execute(script.getName(), bindings);
    if (object == null) {
        return defaultFormatters;
    }
    final PatternFormatter[] patternFormatter = formatterMap.get(object.toString());

    return patternFormatter == null ? defaultFormatters : patternFormatter;
}
 
Example #10
Source File: PatternLayout.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Override
public StringBuilder toSerializable(final LogEvent event, final StringBuilder buffer) {
    final PatternFormatter[] formatters = patternSelector.getFormatters(event);
    final int len = formatters.length;
    for (int i = 0; i < len; i++) {
        formatters[i].format(event, buffer);
    }
    if (replace != null) { // creates temporary objects
        String str = buffer.toString();
        str = replace.format(str);
        buffer.setLength(0);
        buffer.append(str);
    }
    return buffer;
}
 
Example #11
Source File: PatternLayout.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Override
public boolean requiresLocation() {
    for (PatternFormatter formatter : formatters) {
        if (formatter.requiresLocation()) {
            return true;
        }
    }
    return false;
}
 
Example #12
Source File: MarkerPatternSelector.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Override
public PatternFormatter[] getFormatters(final LogEvent event) {
    final Marker marker = event.getMarker();
    if (marker == null) {
        return defaultFormatters;
    }
    for (final String key : formatterMap.keySet()) {
        if (marker.isInstanceOf(key)) {
            return formatterMap.get(key);
        }
    }
    return defaultFormatters;
}
 
Example #13
Source File: ThreadLocalVsPoolBenchmark.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
private void serialize(final StringBuilder stringBuilder) {
    // noinspection ForLoopReplaceableByForEach (avoid iterator instantiation)
    for (int formatterIndex = 0; formatterIndex < FORMATTERS.size(); formatterIndex++) {
        PatternFormatter formatter = FORMATTERS.get(formatterIndex);
        formatter.format(LOG_EVENT, stringBuilder);
    }
}
 
Example #14
Source File: IbisPatternLayout.java    From iaf with Apache License 2.0 5 votes vote down vote up
@Override
public boolean requiresLocation() {
	for (PatternFormatter formatter : formatters) {
		if (formatter.requiresLocation()) {
			return true;
		}
	}
	return false;
}
 
Example #15
Source File: IbisPatternLayout.java    From iaf with Apache License 2.0 5 votes vote down vote up
/**
 * @param pattern the pattern to use or DEFAULT when null
 * @param alwaysWriteExceptions defaults to true
 * @param disableAnsi defaults to false
 * @param noConsoleNoAnsi defaults to false
 */
IbisPatternLayout(final Configuration config, final String pattern, final Charset charset, final boolean alwaysWriteExceptions, final boolean disableAnsi, final boolean noConsoleNoAnsi) {
	super(config, charset);

	try {
		final PatternParser parser = PatternLayout.createPatternParser(configuration);
		final List<PatternFormatter> list = parser.parse(pattern, alwaysWriteExceptions, disableAnsi, noConsoleNoAnsi);
		final PatternFormatter[] formatters = list.toArray(new PatternFormatter[0]);
		serializer = new PatternSerializer(formatters);
	} catch (final RuntimeException ex) {
		throw new IllegalArgumentException("Cannot parse pattern '" + pattern + "'", ex);
	}
}
 
Example #16
Source File: EcsLayout.java    From ecs-logging-java with Apache License 2.0 5 votes vote down vote up
private void serializeAdditionalFieldsAndMDC(LogEvent event, StringBuilder builder) {
    final int length = additionalFields.length;
    if (!event.getContextData().isEmpty() || length > 0) {
        if (length > 0) {
            final StrSubstitutor strSubstitutor = getConfiguration().getStrSubstitutor();
            for (int i = 0; i < length; i++) {
                KeyValuePair additionalField = additionalFields[i];
                PatternFormatter[] formatters = fieldValuePatternFormatter[i];
                CharSequence value = null;
                if (formatters != null) {
                    StringBuilder buffer = EcsJsonSerializer.getMessageStringBuilder();
                    formatPattern(event, formatters, buffer);
                    if (buffer.length() > 0) {
                        value = buffer;
                    }
                } else if (valueNeedsLookup(additionalField.getValue())) {
                    StringBuilder lookupValue = EcsJsonSerializer.getMessageStringBuilder();
                    lookupValue.append(additionalField.getValue());
                    if (strSubstitutor.replaceIn(event, lookupValue)) {
                        value = lookupValue;
                    }
                } else {
                    value = additionalField.getValue();
                }

                if (value != null) {
                    builder.append('\"');
                    JsonUtils.quoteAsString(additionalField.getKey(), builder);
                    builder.append("\":\"");
                    JsonUtils.quoteAsString(EcsJsonSerializer.toNullSafeString(value), builder);
                    builder.append("\",");
                }
            }
        }
        event.getContextData().forEach(WRITE_MDC, builder);
    }
}
 
Example #17
Source File: HighlightErrorConverter.java    From TerminalConsoleAppender with MIT License 5 votes vote down vote up
/**
 * Gets a new instance of the {@link HighlightErrorConverter} with the
 * specified options.
 *
 * @param config The current configuration
 * @param options The pattern options
 * @return The new instance
 */
public static @Nullable HighlightErrorConverter newInstance(Configuration config, String[] options) {
    if (options.length != 1) {
        LOGGER.error("Incorrect number of options on highlightError. Expected 1 received " + options.length);
        return null;
    }
    if (options[0] == null) {
        LOGGER.error("No pattern supplied on highlightError");
        return null;
    }

    PatternParser parser = PatternLayout.createPatternParser(config);
    List<PatternFormatter> formatters = parser.parse(options[0]);
    return new HighlightErrorConverter(formatters);
}
 
Example #18
Source File: HighlightErrorConverter.java    From TerminalConsoleAppender with MIT License 5 votes vote down vote up
@Override
public boolean handlesThrowable() {
    for (final PatternFormatter formatter : formatters) {
        if (formatter.handlesThrowable()) {
            return true;
        }
    }
    return false;
}
 
Example #19
Source File: ConsolePatternSelector.java    From teku with Apache License 2.0 5 votes vote down vote up
public ConsolePatternSelector(
    final AbstractConfiguration configuration, final boolean omitStackTraces) {
  this.omitStackTraces = omitStackTraces;

  final PatternParser patternParser = PatternLayout.createPatternParser(configuration);
  omitStackTraceFormat =
      patternParser.parse(CONSOLE_EXCEPTION_FORMAT, false, true).toArray(PatternFormatter[]::new);
  defaultFormat =
      patternParser.parse(CONSOLE_FORMAT, true, true).toArray(PatternFormatter[]::new);
}
 
Example #20
Source File: LoggerNamePatternSelector.java    From TerminalConsoleAppender with MIT License 5 votes vote down vote up
@Override
public PatternFormatter[] getFormatters(LogEvent event) {
    final @Nullable String loggerName = event.getLoggerName();
    if (loggerName != null) {
        //noinspection ForLoopReplaceableByForEach
        for (int i = 0; i < this.formatters.size(); i++) {
            LoggerNameSelector selector = this.formatters.get(i);
            if (selector.test(loggerName)) {
                return selector.get();
            }
        }
    }

    return this.defaultFormatters;
}
 
Example #21
Source File: JsonPatternLayout.java    From cf-java-logging-support with Apache License 2.0 5 votes vote down vote up
@Override
public String toSerializable(LogEvent event) {
	PatternSelector selector = getSelector(event);
	final StringBuilder buf = getStringBuilder();
	PatternFormatter[] formatters = selector.getFormatters(event);
	final int len = formatters.length;
	for (int i = 0; i < len; i++) {
		formatters[i].format(event, buf);
	}
	String str = buf.toString();
	return str;
}
 
Example #22
Source File: LoggerNamePatternSelector.java    From TerminalConsoleAppender with MIT License 5 votes vote down vote up
/**
 * Constructs a new {@link LoggerNamePatternSelector}.
 *
 * @param defaultPattern The default pattern to use if no logger name matches
 * @param properties The pattern match rules to use
 * @param alwaysWriteExceptions Write exceptions even if pattern does not
 *     include exception conversion
 * @param disableAnsi If true, disable all ANSI escape codes
 * @param noConsoleNoAnsi If true and {@link System#console()} is null,
 *     disable ANSI escape codes
 * @param config The configuration
 */
protected LoggerNamePatternSelector(String defaultPattern, PatternMatch[] properties,
        boolean alwaysWriteExceptions, boolean disableAnsi, boolean noConsoleNoAnsi, Configuration config) {
    PatternParser parser = PatternLayout.createPatternParser(config);
    PatternFormatter[] emptyFormatters = new PatternFormatter[0];
    this.defaultFormatters = parser.parse(defaultPattern, alwaysWriteExceptions, disableAnsi, noConsoleNoAnsi)
            .toArray(emptyFormatters);
    for (PatternMatch property : properties) {
        PatternFormatter[] formatters = parser.parse(property.getPattern(), alwaysWriteExceptions, disableAnsi, noConsoleNoAnsi)
                .toArray(emptyFormatters);
        for (String name : property.getKey().split(",")) {
            this.formatters.add(new LoggerNameSelector(name, formatters));
        }
    }
}
 
Example #23
Source File: PatternLayout.java    From logging-log4j2 with Apache License 2.0 4 votes vote down vote up
private PatternSerializer(final PatternFormatter[] formatters, final RegexReplacement replace) {
    super();
    this.formatters = formatters;
    this.replace = replace;
}
 
Example #24
Source File: Rfc5424Layout.java    From logging-log4j2 with Apache License 2.0 4 votes vote down vote up
public FieldFormatter(final Map<String, List<PatternFormatter>> fieldMap, final boolean discardIfEmpty) {
    this.discardIfEmpty = discardIfEmpty;
    this.delegateMap = fieldMap;
}
 
Example #25
Source File: EcsLayout.java    From ecs-logging-java with Apache License 2.0 4 votes vote down vote up
private static void formatPattern(LogEvent event, PatternFormatter[] formatters, StringBuilder buffer) {
    final int len = formatters.length;
    for (int i = 0; i < len; i++) {
        formatters[i].format(event, buffer);
    }
}
 
Example #26
Source File: ConsolePatternSelector.java    From teku with Apache License 2.0 4 votes vote down vote up
@Override
public PatternFormatter[] getFormatters(final LogEvent event) {
  return omitStackTraces && event.getThrownProxy() != null ? omitStackTraceFormat : defaultFormat;
}
 
Example #27
Source File: LoggerNamePatternSelector.java    From TerminalConsoleAppender with MIT License 4 votes vote down vote up
LoggerNameSelector(String name, PatternFormatter[] formatters) {
    this.name = name;
    this.isPackage = name.endsWith(".");
    this.formatters = formatters;
}
 
Example #28
Source File: LoggerNamePatternSelector.java    From TerminalConsoleAppender with MIT License 4 votes vote down vote up
PatternFormatter[] get() {
    return this.formatters;
}
 
Example #29
Source File: NoGcLayout.java    From logging-log4j2 with Apache License 2.0 4 votes vote down vote up
private PatternSerializer2(final PatternFormatter[] formatters) {
    super();
    this.formatters = formatters;
}
 
Example #30
Source File: NoGcLayout.java    From logging-log4j2 with Apache License 2.0 4 votes vote down vote up
PatternSerializer2() {
    this(new PatternFormatter[]{
            new PatternFormatter(NoGcMessagePatternConverter.newInstance(null, null),
                    FormattingInfo.getDefault()),
    });
}