Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions CHANGELOG.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,21 @@ See Telemetry in the https://rocketraman.github.io/bootable/[documentation].
* `JdbcDataSourceService` takes ``DataSourceWrapper``s as its third argument.
* Metro's `JdbcDataSourceBindings` is now an interface.

=== Structured logging

See Logging in the https://rocketraman.github.io/bootable/[documentation].

* `StructuredMessage` is a Log4j2 message with a text and typed fields.
* The `JSON` and `GCLOUD` output types write a map message's fields as top-level JSON fields.
* The text output types write a `StructuredMessage`'s fields after its text, with a `%fields` converter.
* `JSON` writes the trace and span ids as ECS's `trace.id` and `span.id`.
* `JSON` writes the source location as ECS's `log.origin.*` fields when `LOGGING_LOCATION_ENABLED` is set.

==== Breaking changes

* `JSON` no longer writes the logging context's `trace_id`, `span_id`, and `trace_flags` as fields of those names.
* `JSON` and `GCLOUD` also write an existing map message's entries, such as a `StringMapMessage`'s, as top-level fields.

=== HTTP clients (Ktor)

See the HTTP client in the https://rocketraman.github.io/bootable/[documentation].
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
package com.github.rocketraman.bootable.logging.log4j2;

import org.apache.logging.log4j.core.LogEvent;
import org.apache.logging.log4j.core.config.plugins.Plugin;
import org.apache.logging.log4j.core.pattern.ConverterKeys;
import org.apache.logging.log4j.core.pattern.LogEventPatternConverter;
import org.apache.logging.log4j.core.pattern.PatternConverter;

/**
* The {@code %fields} pattern converter.
* Converts a log message of type {@link StructuredMessage} to its fields, as {@code {key=value, ...}}.
* Ignores other messages.
*
* <p>Bootable's text layouts use this converter, not Log4j's {@code %K}, because {@code %K} writes the entries of every
* map message, not just a {@link StructuredMessage}'s.
* For a {@code StringMapMessage}, {@code %m} already writes its entries, as {@code key="value"}, so {@code %K} would
* write them a second time on the same line.
*
* <p>Written in Java because Log4j's plugin annotation processor runs in javac, on Java sources.
* It registers this class as a plugin, and generates its GraalVM reflection metadata.
* The Kotlin compiler doesn't run annotation processors, so a Kotlin class would need kapt.
* The formatting itself is in Kotlin, in {@code formatFields}.
*/
@Plugin(name = "FieldsPatternConverter", category = PatternConverter.CATEGORY)
@ConverterKeys({"fields"})
public final class FieldsPatternConverter extends LogEventPatternConverter {

private static final FieldsPatternConverter INSTANCE = new FieldsPatternConverter();

private FieldsPatternConverter() {
super("Fields", "fields");
}

/** The converter; it takes no options. */
public static FieldsPatternConverter newInstance(final String[] options) {
return INSTANCE;
}

@Override
public void format(final LogEvent event, final StringBuilder toAppendTo) {
FieldsFormat.formatFields(event, toAppendTo);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
@file:JvmName("FieldsFormat")

package com.github.rocketraman.bootable.logging.log4j2

import org.apache.logging.log4j.core.LogEvent

/**
* Appends the fields of [event]'s message to [buffer] as `{key=value, ...}`, for the `%fields` pattern converter,
* [FieldsPatternConverter].
* Appends nothing if the message isn't a [StructuredMessage], or has no fields.
*/
internal fun formatFields(event: LogEvent, buffer: StringBuilder) {
val fields = (event.message as? StructuredMessage)?.fields
if (fields.isNullOrEmpty()) return
fields.entries.joinTo(buffer, prefix = "{", postfix = "}") { (key, value) -> "$key=$value" }
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
package com.github.rocketraman.bootable.logging.log4j2

import org.apache.logging.log4j.message.MapMessage

/**
* A log message with a human-readable [message], and typed key/value fields that a log backend can index.
*
* Bootable's JSON layouts write each field as a top-level field of the event, alongside `message`, which holds
* only the [message].
* A number or a boolean stays a JSON number or boolean; any other value is written as its `toString()`.
* The text layouts write the fields after the text, as `{key=value, ...}`.
*
* A field whose value is `null` is left out.
* Name the fields after the backend's schema, such as the
* [Elastic Common Schema](https://www.elastic.co/guide/en/ecs/current/ecs-field-reference.html)'s
* `http.request.method` or `event.duration`, so that it reads them without mapping.
* A field must not have the same name as an existing output field, such as `message` or `@timestamp`.
* The event would then have two fields with that name.
* Bootable's logging documentation lists the fields each output type writes.
*
* Log one through Log4j's API, like any other message:
*
* ```
* log.info(StructuredMessage("order placed", "order.id" to order.id, "order.total" to order.total))
* ```
*
* Or subclass it for an event of a type of your own, to take the fields from that type:
*
* ```
* class OrderPlaced(order: Order) : StructuredMessage(
* "order ${order.id} placed",
* "order.id" to order.id,
* "order.total" to order.total,
* "customer.id" to order.customerId,
* )
*
* log.info(OrderPlaced(order))
* ```
*
* Log4j's own [StructuredDataMessage][org.apache.logging.log4j.message.StructuredDataMessage] is for syslog's
* RFC 5424 structured data, as Log4j's `Rfc5424Layout` writes it.
* It needs a structured data id and an event type, limits keys to 32 printable ASCII characters, and holds only
* strings.
* Its message is the structured data in syslog's format, `type [id key="value" ...] text`, so a JSON layout's
* `message` holds that rather than the text.
* For JSON output, use this instead: its message is the text alone, and its fields keep their types.
*/
open class StructuredMessage(
val message: String,
fields: Map<String, Any?>,
) : MapMessage<StructuredMessage, Any>(fields.size) {

constructor(message: String, vararg fields: Pair<String, Any?>) : this(message, fields.toMap())

/** The fields, without those whose value was `null`. */
val fields: Map<String, Any> = buildMap { fields.forEach { (key, value) -> if (value != null) put(key, value) } }

init {
this.fields.forEach { (key, value) -> with(key, value) }
}

override fun getFormattedMessage(): String = message

// JsonTemplateLayout's message resolver, and PatternLayout's %m, format a StringBuilderFormattable message, which a
// MapMessage is, with formatTo rather than getFormattedMessage: both must give the text alone. The JSON layouts' map
// resolver writes the fields from the MapMessage's entries, and the text layouts' %fields converter from [fields].
override fun formatTo(buffer: StringBuilder) {
buffer.append(message)
}

override fun newInstance(map: Map<String, Any>): StructuredMessage = StructuredMessage(message, map)

override fun toString(): String = "StructuredMessage(message=$message, fields=$fields)"
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,10 @@
<Appenders>
<!-- Setting direct to false can cause a race with standard i/o redirection -->
<Console name="Console" direct="${env:LOGGING_CONSOLE_DIRECT:-${sys:logging.console.direct:-true}}">
<JsonTemplateLayout eventTemplateUri="classpath:GcpLayout.json" locationInfoEnabled="${env:LOGGING_LOCATION_ENABLED:-${sys:logging.location.enabled:-false}}"/>
<JsonTemplateLayout eventTemplateUri="classpath:GcpLayout.json" locationInfoEnabled="${env:LOGGING_LOCATION_ENABLED:-${sys:logging.location.enabled:-false}}">
<!-- a StructuredMessage's fields, or any MapMessage's entries, as top-level fields -->
<EventTemplateAdditionalField key="fields" format="JSON" value='{"$resolver": "map", "flatten": true}'/>
</JsonTemplateLayout>
</Console>
</Appenders>
<Loggers>
Expand Down
15 changes: 14 additions & 1 deletion boot-logging-log4j2/src/main/resources/log4j2-base-json.xml
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,20 @@
<Appenders>
<!-- Setting direct to false can cause a race with standard i/o redirection -->
<Console name="Console" direct="${env:LOGGING_CONSOLE_DIRECT:-${sys:logging.console.direct:-true}}">
<JsonTemplateLayout locationInfoEnabled="${env:LOGGING_LOCATION_ENABLED:-${sys:logging.location.enabled:-false}}"/>
<!--
Log4j's Elastic Common Schema template, plus the structured fields, the source location, and the OpenTelemetry
trace and span as ECS's trace.id and span.id. An additional field replaces the template's field of the same key:
labels replaces the template's, to leave the trace context out of the flattened MDC.
-->
<JsonTemplateLayout eventTemplateUri="classpath:EcsLayout.json" locationInfoEnabled="${env:LOGGING_LOCATION_ENABLED:-${sys:logging.location.enabled:-false}}">
<EventTemplateAdditionalField key="labels" format="JSON" value='{"$resolver": "mdc", "pattern": "^(?!(trace_id|span_id|trace_flags)$).*", "flatten": true, "stringified": true}'/>
<EventTemplateAdditionalField key="trace.id" format="JSON" value='{"$resolver": "mdc", "key": "trace_id"}'/>
<EventTemplateAdditionalField key="span.id" format="JSON" value='{"$resolver": "mdc", "key": "span_id"}'/>
<EventTemplateAdditionalField key="log.origin.file.name" format="JSON" value='{"$resolver": "source", "field": "fileName"}'/>
<EventTemplateAdditionalField key="log.origin.file.line" format="JSON" value='{"$resolver": "source", "field": "lineNumber"}'/>
<EventTemplateAdditionalField key="log.origin.function" format="JSON" value='{"$resolver": "source", "field": "methodName"}'/>
<EventTemplateAdditionalField key="fields" format="JSON" value='{"$resolver": "map", "flatten": true}'/>
</JsonTemplateLayout>
</Console>
</Appenders>
<Loggers>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
<Appenders>
<!-- Setting direct to false can cause a race with standard i/o redirection -->
<Console name="Console" direct="${env:LOGGING_CONSOLE_DIRECT:-${sys:logging.console.direct:-true}}">
<PatternLayout disableAnsi="true" pattern="%d{${LOG_DATEFORMAT_PATTERN:-yyyy-MM-dd HH:mm:ss.SSS}} %highlight{${LOG_LEVEL_PATTERN:-%5p}}{FATAL=red blink, ERROR=red, WARN=yellow bold, INFO=green, DEBUG=green bold, TRACE=blue} [%15.15t] %style{%-40.40c{1.}}{cyan} : %X %m%n${LOG_EXCEPTION_CONVERSION_WORD:-%xEx}"/>
<PatternLayout disableAnsi="true" pattern="%d{${LOG_DATEFORMAT_PATTERN:-yyyy-MM-dd HH:mm:ss.SSS}} %highlight{${LOG_LEVEL_PATTERN:-%5p}}{FATAL=red blink, ERROR=red, WARN=yellow bold, INFO=green, DEBUG=green bold, TRACE=blue} [%15.15t] %style{%-40.40c{1.}}{cyan} : %X %m%notEmpty{ %fields}%n${LOG_EXCEPTION_CONVERSION_WORD:-%xEx}"/>
</Console>
</Appenders>
<Loggers>
Expand Down
2 changes: 1 addition & 1 deletion boot-logging-log4j2/src/main/resources/log4j2-base.xml
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
<Appenders>
<!-- Setting direct to false can cause a race with standard i/o redirection -->
<Console name="Console" direct="${env:LOGGING_CONSOLE_DIRECT:-${sys:logging.console.direct:-true}}">
<PatternLayout disableAnsi="${env:LOGGING_ANSI_DISABLE:-${sys:logging.ansi.disable:-false}}" pattern="%d{${LOG_DATEFORMAT_PATTERN:-yyyy-MM-dd HH:mm:ss.SSS}} %highlight{${LOG_LEVEL_PATTERN:-%5p}}{FATAL=red blink, ERROR=red, WARN=yellow bold, INFO=green, DEBUG=green bold, TRACE=blue} [%15.15t] %style{%-40.40c{1.}}{cyan} : %X %m%n${LOG_EXCEPTION_CONVERSION_WORD:-%xEx}"/>
<PatternLayout disableAnsi="${env:LOGGING_ANSI_DISABLE:-${sys:logging.ansi.disable:-false}}" pattern="%d{${LOG_DATEFORMAT_PATTERN:-yyyy-MM-dd HH:mm:ss.SSS}} %highlight{${LOG_LEVEL_PATTERN:-%5p}}{FATAL=red blink, ERROR=red, WARN=yellow bold, INFO=green, DEBUG=green bold, TRACE=blue} [%15.15t] %style{%-40.40c{1.}}{cyan} : %X %m%notEmpty{ %fields}%n${LOG_EXCEPTION_CONVERSION_WORD:-%xEx}"/>
</Console>
</Appenders>
<Loggers>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
package com.github.rocketraman.bootable.logging.log4j2

import de.infix.testBalloon.framework.core.testSuite
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonPrimitive
import kotlinx.serialization.json.jsonObject
import org.apache.logging.log4j.Level
import org.apache.logging.log4j.core.Layout
import org.apache.logging.log4j.core.LogEvent
import org.apache.logging.log4j.core.config.ConfigurationSource
import org.apache.logging.log4j.core.config.xml.XmlConfiguration
import org.apache.logging.log4j.core.impl.Log4jLogEvent
import org.apache.logging.log4j.message.SimpleMessage
import org.apache.logging.log4j.message.StringMapMessage
import org.apache.logging.log4j.util.SortedArrayStringMap

/** The layout of the `Console` appender in one of Bootable's base configs, as `loggingInit` would load it. */
private fun consoleLayout(resource: String): Layout<*> {
val source = ConfigurationSource.fromResource(resource, StructuredMessage::class.java.classLoader)
val config = XmlConfiguration(null, source)
config.initialize()
config.start()
return config.getAppender<org.apache.logging.log4j.core.Appender>("Console").layout
}

private fun event(
message: org.apache.logging.log4j.message.Message,
context: Map<String, String> = emptyMap(),
thrown: Throwable? = null,
): LogEvent = Log4jLogEvent.newBuilder()
.setLoggerName("com.example.Orders")
.setLevel(Level.INFO)
.setMessage(message)
.setContextData(SortedArrayStringMap(context))
.setThrown(thrown)
.build()

private fun Layout<*>.render(event: LogEvent): String = String(toByteArray(event), Charsets.UTF_8)

private fun Layout<*>.renderJson(event: LogEvent): JsonObject = Json.parseToJsonElement(render(event)).jsonObject

private val orderPlaced = StructuredMessage(
"order 42 placed",
"order.id" to "42",
"order.total" to 1250L,
"order.gift" to true,
"order.note" to null,
)

private val otelContext = mapOf(
"trace_id" to "4bf92f3577b34da6a3ce929d0e0e4736",
"span_id" to "00f067aa0ba902b7",
"trace_flags" to "01",
"tenant" to "acme",
)

val StructuredMessageLayoutTest by testSuite {
test("the message is the text alone, and the fields are its map entries without nulls") {
assert(orderPlaced.formattedMessage == "order 42 placed")
assert(orderPlaced.fields == mapOf("order.id" to "42", "order.total" to 1250L, "order.gift" to true))
assert(orderPlaced.get("order.total") == "1250")
assert(!orderPlaced.containsKey("order.note"))
}

test("GCLOUD writes the fields as typed top-level fields, beside Cloud Logging's trace and span") {
val json = consoleLayout("log4j2-base-json-gcloud.xml").renderJson(event(orderPlaced, otelContext))
assert(json["message"] == JsonPrimitive("order 42 placed"))
assert(json["order.id"] == JsonPrimitive("42"))
assert(json["order.total"] == JsonPrimitive(1250))
assert(json["order.gift"] == JsonPrimitive(true))
assert("fields" !in json)
assert(json["logging.googleapis.com/trace"] == JsonPrimitive("4bf92f3577b34da6a3ce929d0e0e4736"))
assert(json["logging.googleapis.com/spanId"] == JsonPrimitive("00f067aa0ba902b7"))
}

test("JSON writes the typed fields and the logging context at top level, and the trace and span as ECS's") {
val json = consoleLayout("log4j2-base-json.xml").renderJson(event(orderPlaced, otelContext))
assert(json["ecs.version"] == JsonPrimitive("1.2.0"))
assert(json["log.level"] == JsonPrimitive("INFO"))
assert(json["log.logger"] == JsonPrimitive("com.example.Orders"))
assert(json["message"] == JsonPrimitive("order 42 placed"))
assert(json["order.id"] == JsonPrimitive("42"))
assert(json["order.total"] == JsonPrimitive(1250))
assert(json["order.gift"] == JsonPrimitive(true))
assert(json["trace.id"] == JsonPrimitive("4bf92f3577b34da6a3ce929d0e0e4736"))
assert(json["span.id"] == JsonPrimitive("00f067aa0ba902b7"))
assert(json["tenant"] == JsonPrimitive("acme"))
assert("trace_id" !in json && "span_id" !in json && "trace_flags" !in json)
assert("fields" !in json && "labels" !in json)
}

test("JSON writes an exception as ECS's error fields") {
val json = consoleLayout("log4j2-base-json.xml")
.renderJson(event(SimpleMessage("failed"), thrown = IllegalStateException("boom")))
assert(json["error.type"] == JsonPrimitive("java.lang.IllegalStateException"))
assert(json["error.message"] == JsonPrimitive("boom"))
assert("trace.id" !in json)
assert("log.origin.function" !in json)
}

test("JSON writes the source location as ECS's log.origin fields when it is enabled") {
System.setProperty("logging.location.enabled", "true")
val layout = try {
consoleLayout("log4j2-base-json.xml")
} finally {
System.clearProperty("logging.location.enabled")
}
val event = Log4jLogEvent.newBuilder()
.setLoggerName("com.example.Orders")
.setLevel(Level.INFO)
.setMessage(SimpleMessage("placed"))
.setSource(StackTraceElement("com.example.Orders", "place", "Orders.kt", 12))
.setIncludeLocation(true)
.build()
val json = layout.renderJson(event)
assert(json["log.origin.file.name"] == JsonPrimitive("Orders.kt"))
assert(json["log.origin.file.line"] == JsonPrimitive(12))
assert(json["log.origin.function"] == JsonPrimitive("place"))
}

test("the text layouts write the fields after the text, and nothing more for other messages") {
for (resource in listOf("log4j2-base.xml", "log4j2-base-plain.xml")) {
val layout = consoleLayout(resource)
val line = layout.render(event(orderPlaced)).trimEnd()
assert(line.endsWith(" order 42 placed {order.id=42, order.total=1250, order.gift=true}"))
val plain = layout.render(event(SimpleMessage("hello"))).trimEnd()
assert(plain.endsWith(" hello"))
// a map message's %m is its entries already: they aren't written twice
val map = layout.render(event(StringMapMessage().with("http.status", "200"))).trimEnd()
assert(map.endsWith(""" http.status="200""""))
}
}
}
10 changes: 10 additions & 0 deletions build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -1063,6 +1063,16 @@ project("boot-logging-log4j2") {
api(rootProject.libs.kotlin.reflect)
implementation(platform(rootProject.libs.log4j.bom))
implementation(rootProject.libs.bundles.log4j.impl)
// registers FieldsPatternConverter as a Log4j plugin, with its GraalVM native metadata
annotationProcessor(rootProject.libs.log4j.core)
testImplementation(rootProject.libs.kotlinx.serialization.json)
}

tasks.named<JavaCompile>("compileJava") {
options.compilerArgs.addAll(listOf(
"-Alog4j.graalvm.groupId=${project.group}",
"-Alog4j.graalvm.artifactId=${project.name}",
))
}
}

Expand Down
2 changes: 1 addition & 1 deletion docs/modules.yml
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ functions:
note: comes with `boot`; add it yourself to call its API, such as `LoggingType`
modules:
- name: boot-logging-log4j2
provides: Log4j2, with layouts for plain, coloured, JSON, and Google Cloud output
provides: Log4j2, with layouts for plain, coloured, Elastic Common Schema JSON, and Google Cloud output, and `StructuredMessage` for structured fields
page: logging:index.adoc
- title: Core
choice: implied
Expand Down
Loading
Loading