|
| 1 | +/* |
| 2 | + * Copyright 2012-2024 the original author or authors. |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * https://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + */ |
| 16 | + |
| 17 | +package org.springframework.boot.logging.log4j2; |
| 18 | + |
| 19 | +import java.math.BigDecimal; |
| 20 | +import java.util.Objects; |
| 21 | +import java.util.Set; |
| 22 | +import java.util.function.BiConsumer; |
| 23 | +import java.util.regex.Pattern; |
| 24 | + |
| 25 | +import org.apache.commons.logging.Log; |
| 26 | +import org.apache.commons.logging.LogFactory; |
| 27 | +import org.apache.logging.log4j.Level; |
| 28 | +import org.apache.logging.log4j.core.LogEvent; |
| 29 | +import org.apache.logging.log4j.core.net.Severity; |
| 30 | +import org.apache.logging.log4j.core.time.Instant; |
| 31 | +import org.apache.logging.log4j.message.Message; |
| 32 | +import org.apache.logging.log4j.util.ReadOnlyStringMap; |
| 33 | + |
| 34 | +import org.springframework.boot.json.JsonWriter; |
| 35 | +import org.springframework.boot.json.JsonWriter.WritableJson; |
| 36 | +import org.springframework.boot.logging.structured.CommonStructuredLogFormat; |
| 37 | +import org.springframework.boot.logging.structured.GraylogExtendedLogFormatService; |
| 38 | +import org.springframework.boot.logging.structured.JsonWriterStructuredLogFormatter; |
| 39 | +import org.springframework.boot.logging.structured.StructuredLogFormatter; |
| 40 | +import org.springframework.core.env.Environment; |
| 41 | +import org.springframework.core.log.LogMessage; |
| 42 | +import org.springframework.util.Assert; |
| 43 | +import org.springframework.util.ObjectUtils; |
| 44 | + |
| 45 | +/** |
| 46 | + * Log4j2 {@link StructuredLogFormatter} for |
| 47 | + * {@link CommonStructuredLogFormat#GRAYLOG_EXTENDED_LOG_FORMAT}. Supports GELF version |
| 48 | + * 1.1. |
| 49 | + * |
| 50 | + * @author Samuel Lissner |
| 51 | + * @author Moritz Halbritter |
| 52 | + */ |
| 53 | +class GraylogExtendedLogFormatStructuredLogFormatter extends JsonWriterStructuredLogFormatter<LogEvent> { |
| 54 | + |
| 55 | + private static final Log logger = LogFactory.getLog(GraylogExtendedLogFormatStructuredLogFormatter.class); |
| 56 | + |
| 57 | + /** |
| 58 | + * Allowed characters in field names are any word character (letter, number, |
| 59 | + * underscore), dashes and dots. |
| 60 | + */ |
| 61 | + private static final Pattern FIELD_NAME_VALID_PATTERN = Pattern.compile("^[\\w.\\-]*$"); |
| 62 | + |
| 63 | + /** |
| 64 | + * Every field been sent and prefixed with an underscore "_" will be treated as an |
| 65 | + * additional field. |
| 66 | + */ |
| 67 | + private static final String ADDITIONAL_FIELD_PREFIX = "_"; |
| 68 | + |
| 69 | + /** |
| 70 | + * Libraries SHOULD not allow to send id as additional field ("_id"). Graylog server |
| 71 | + * nodes omit this field automatically. |
| 72 | + */ |
| 73 | + private static final Set<String> ADDITIONAL_FIELD_ILLEGAL_KEYS = Set.of("id", "_id"); |
| 74 | + |
| 75 | + GraylogExtendedLogFormatStructuredLogFormatter(Environment environment) { |
| 76 | + super((members) -> jsonMembers(environment, members)); |
| 77 | + } |
| 78 | + |
| 79 | + private static void jsonMembers(Environment environment, JsonWriter.Members<LogEvent> members) { |
| 80 | + members.add("version", "1.1"); |
| 81 | + // note: a blank message will lead to a Graylog error as of Graylog v6.0.x. We are |
| 82 | + // ignoring this here. |
| 83 | + members.add("short_message", LogEvent::getMessage).as(Message::getFormattedMessage); |
| 84 | + members.add("timestamp", LogEvent::getInstant) |
| 85 | + .as(GraylogExtendedLogFormatStructuredLogFormatter::formatTimeStamp); |
| 86 | + members.add("level", GraylogExtendedLogFormatStructuredLogFormatter::convertLevel); |
| 87 | + members.add("_level_name", LogEvent::getLevel).as(Level::name); |
| 88 | + members.add("_process_pid", environment.getProperty("spring.application.pid", Long.class)) |
| 89 | + .when(Objects::nonNull); |
| 90 | + members.add("_process_thread_name", LogEvent::getThreadName); |
| 91 | + GraylogExtendedLogFormatService.get(environment).jsonMembers(members); |
| 92 | + members.add("_log_logger", LogEvent::getLoggerName); |
| 93 | + members.from(LogEvent::getContextData) |
| 94 | + .whenNot(ReadOnlyStringMap::isEmpty) |
| 95 | + .usingPairs((contextData, pairs) -> contextData |
| 96 | + .forEach((key, value) -> createAdditionalField(key, value, pairs))); |
| 97 | + members.add().whenNotNull(LogEvent::getThrownProxy).usingMembers((eventMembers) -> { |
| 98 | + eventMembers.add("full_message", |
| 99 | + GraylogExtendedLogFormatStructuredLogFormatter::formatFullMessageWithThrowable); |
| 100 | + eventMembers.add("_error_type", (event) -> event.getThrownProxy().getThrowable()) |
| 101 | + .whenNotNull() |
| 102 | + .as(ObjectUtils::nullSafeClassName); |
| 103 | + eventMembers.add("_error_stack_trace", (event) -> event.getThrownProxy().getExtendedStackTraceAsString()); |
| 104 | + eventMembers.add("_error_message", (event) -> event.getThrownProxy().getMessage()); |
| 105 | + }); |
| 106 | + } |
| 107 | + |
| 108 | + /** |
| 109 | + * GELF requires "seconds since UNIX epoch with optional <b>decimal places for |
| 110 | + * milliseconds</b>". To comply with this requirement, we format a POSIX timestamp |
| 111 | + * with millisecond precision as e.g. "1725459730385" -> "1725459730.385" |
| 112 | + * @param timeStamp the timestamp of the log message. Note it is not the standard Java |
| 113 | + * `Instant` type but {@link org.apache.logging.log4j.core.time} |
| 114 | + * @return the timestamp formatted as string with millisecond precision |
| 115 | + */ |
| 116 | + private static WritableJson formatTimeStamp(Instant timeStamp) { |
| 117 | + return (out) -> out.append(new BigDecimal(timeStamp.getEpochMillisecond()).movePointLeft(3).toPlainString()); |
| 118 | + } |
| 119 | + |
| 120 | + /** |
| 121 | + * Converts the log4j2 event level to the Syslog event level code. |
| 122 | + * @param event the log event |
| 123 | + * @return an integer representing the syslog log level code |
| 124 | + * @see Severity class from Log4j2 which contains the conversion logic |
| 125 | + */ |
| 126 | + private static int convertLevel(LogEvent event) { |
| 127 | + return Severity.getSeverity(event.getLevel()).getCode(); |
| 128 | + } |
| 129 | + |
| 130 | + private static String formatFullMessageWithThrowable(LogEvent event) { |
| 131 | + return event.getMessage().getFormattedMessage() + "\n\n" |
| 132 | + + event.getThrownProxy().getExtendedStackTraceAsString(); |
| 133 | + } |
| 134 | + |
| 135 | + private static void createAdditionalField(String fieldName, Object value, BiConsumer<Object, Object> pairs) { |
| 136 | + Assert.notNull(fieldName, "fieldName must not be null"); |
| 137 | + if (!FIELD_NAME_VALID_PATTERN.matcher(fieldName).matches()) { |
| 138 | + logger.warn(LogMessage.format("'%s' is not a valid field name according to GELF standard", fieldName)); |
| 139 | + return; |
| 140 | + } |
| 141 | + if (ADDITIONAL_FIELD_ILLEGAL_KEYS.contains(fieldName)) { |
| 142 | + logger.warn(LogMessage.format("'%s' is an illegal field name according to GELF standard", fieldName)); |
| 143 | + return; |
| 144 | + } |
| 145 | + String key = (fieldName.startsWith(ADDITIONAL_FIELD_PREFIX)) ? fieldName : ADDITIONAL_FIELD_PREFIX + fieldName; |
| 146 | + pairs.accept(key, value); |
| 147 | + } |
| 148 | + |
| 149 | +} |
0 commit comments