diff --git a/CHANGELOG.adoc b/CHANGELOG.adoc
index 8cad0370..62b31e07 100644
--- a/CHANGELOG.adoc
+++ b/CHANGELOG.adoc
@@ -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].
diff --git a/boot-logging-log4j2/src/main/java/com/github/rocketraman/bootable/logging/log4j2/FieldsPatternConverter.java b/boot-logging-log4j2/src/main/java/com/github/rocketraman/bootable/logging/log4j2/FieldsPatternConverter.java
new file mode 100644
index 00000000..f833d299
--- /dev/null
+++ b/boot-logging-log4j2/src/main/java/com/github/rocketraman/bootable/logging/log4j2/FieldsPatternConverter.java
@@ -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.
+ *
+ *
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.
+ *
+ *
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);
+ }
+}
diff --git a/boot-logging-log4j2/src/main/kotlin/com/github/rocketraman/bootable/logging/log4j2/FieldsFormat.kt b/boot-logging-log4j2/src/main/kotlin/com/github/rocketraman/bootable/logging/log4j2/FieldsFormat.kt
new file mode 100644
index 00000000..147debd2
--- /dev/null
+++ b/boot-logging-log4j2/src/main/kotlin/com/github/rocketraman/bootable/logging/log4j2/FieldsFormat.kt
@@ -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" }
+}
diff --git a/boot-logging-log4j2/src/main/kotlin/com/github/rocketraman/bootable/logging/log4j2/StructuredMessage.kt b/boot-logging-log4j2/src/main/kotlin/com/github/rocketraman/bootable/logging/log4j2/StructuredMessage.kt
new file mode 100644
index 00000000..fe27ca53
--- /dev/null
+++ b/boot-logging-log4j2/src/main/kotlin/com/github/rocketraman/bootable/logging/log4j2/StructuredMessage.kt
@@ -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,
+) : MapMessage(fields.size) {
+
+ constructor(message: String, vararg fields: Pair) : this(message, fields.toMap())
+
+ /** The fields, without those whose value was `null`. */
+ val fields: Map = 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): StructuredMessage = StructuredMessage(message, map)
+
+ override fun toString(): String = "StructuredMessage(message=$message, fields=$fields)"
+}
diff --git a/boot-logging-log4j2/src/main/resources/log4j2-base-json-gcloud.xml b/boot-logging-log4j2/src/main/resources/log4j2-base-json-gcloud.xml
index 77ff1c71..cf9553a6 100644
--- a/boot-logging-log4j2/src/main/resources/log4j2-base-json-gcloud.xml
+++ b/boot-logging-log4j2/src/main/resources/log4j2-base-json-gcloud.xml
@@ -3,7 +3,10 @@
-
+
+
+
+
diff --git a/boot-logging-log4j2/src/main/resources/log4j2-base-json.xml b/boot-logging-log4j2/src/main/resources/log4j2-base-json.xml
index e6c8964c..d9372a35 100644
--- a/boot-logging-log4j2/src/main/resources/log4j2-base-json.xml
+++ b/boot-logging-log4j2/src/main/resources/log4j2-base-json.xml
@@ -3,7 +3,20 @@
-
+
+
+
+
+
+
+
+
+
+
diff --git a/boot-logging-log4j2/src/main/resources/log4j2-base-plain.xml b/boot-logging-log4j2/src/main/resources/log4j2-base-plain.xml
index 4edc0c5f..f9f2cf54 100644
--- a/boot-logging-log4j2/src/main/resources/log4j2-base-plain.xml
+++ b/boot-logging-log4j2/src/main/resources/log4j2-base-plain.xml
@@ -3,7 +3,7 @@
-
+
diff --git a/boot-logging-log4j2/src/main/resources/log4j2-base.xml b/boot-logging-log4j2/src/main/resources/log4j2-base.xml
index ad38d18d..b71785ed 100644
--- a/boot-logging-log4j2/src/main/resources/log4j2-base.xml
+++ b/boot-logging-log4j2/src/main/resources/log4j2-base.xml
@@ -3,7 +3,7 @@
-
+
diff --git a/boot-logging-log4j2/src/test/kotlin/com/github/rocketraman/bootable/logging/log4j2/StructuredMessageLayoutTest.kt b/boot-logging-log4j2/src/test/kotlin/com/github/rocketraman/bootable/logging/log4j2/StructuredMessageLayoutTest.kt
new file mode 100644
index 00000000..e5d18a4d
--- /dev/null
+++ b/boot-logging-log4j2/src/test/kotlin/com/github/rocketraman/bootable/logging/log4j2/StructuredMessageLayoutTest.kt
@@ -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("Console").layout
+}
+
+private fun event(
+ message: org.apache.logging.log4j.message.Message,
+ context: Map = 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""""))
+ }
+ }
+}
diff --git a/build.gradle.kts b/build.gradle.kts
index ecea8e0e..42880049 100644
--- a/build.gradle.kts
+++ b/build.gradle.kts
@@ -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("compileJava") {
+ options.compilerArgs.addAll(listOf(
+ "-Alog4j.graalvm.groupId=${project.group}",
+ "-Alog4j.graalvm.artifactId=${project.name}",
+ ))
}
}
diff --git a/docs/modules.yml b/docs/modules.yml
index 1918404a..2126419a 100644
--- a/docs/modules.yml
+++ b/docs/modules.yml
@@ -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
diff --git a/docs/modules/logging/pages/index.adoc b/docs/modules/logging/pages/index.adoc
index 412a9f23..063fb8ed 100644
--- a/docs/modules/logging/pages/index.adoc
+++ b/docs/modules/logging/pages/index.adoc
@@ -1,7 +1,7 @@
= Logging (Log4j2)
-:description: Log4j2 to the console, as plain or coloured text, JSON, or Google Cloud's JSON, set up before anything else runs.
+:description: Log4j2 to the console, as plain or coloured text, Elastic Common Schema JSON, or Google Cloud's JSON, with structured fields, set up before anything else runs.
-`boot-logging-log4j2` makes https://logging.apache.org/log4j/2.x/[Log4j2] the application's logging, with a console appender in one of several output types: coloured or plain text, JSON, or Google Cloud's structured JSON.
+`boot-logging-log4j2` makes https://logging.apache.org/log4j/2.x/[Log4j2] the application's logging, with a console appender in one of several output types: coloured or plain text, Elastic Common Schema JSON, or Google Cloud's structured JSON.
It routes the other logging APIs to Log4j2 too: SLF4J, `java.util.logging`, and the standard output and error streams.
`boot { }` initializes logging before anything else, before it builds the application, so config loading and the application's construction log with the chosen output.
@@ -17,7 +17,7 @@ modules::logging[]
== Install
`boot` brings `boot-logging-log4j2` at runtime, since `boot { }` initializes it.
-Add it as a dependency to use its API in your code: `LoggingType`, `loggingInit`, and Log4j's Kotlin API.
+Add it as a dependency to use its API in your code: `LoggingType`, `loggingInit`, `StructuredMessage`, and Log4j's Kotlin API.
install::[boot-logging-log4j2]
@@ -34,6 +34,48 @@ include::ROOT:example$vanilla/logging/Logging.kt[tag=logger]
A library that logs through SLF4J or `java.util.logging` logs through Log4j2 too, with the same output.
+[#fields]
+=== Structured fields
+
+A `StructuredMessage` is a message with typed fields beside its text, for a backend to index and query, such as an order's id and total:
+
+[source,kotlin]
+----
+include::ROOT:example$vanilla/logging/Logging.kt[tag=fields]
+----
+
+The JSON output types write each field as a top-level field of the event, and `message` holds the text alone:
+
+[source,json]
+----
+{"@timestamp":"2026-11-25T09:30:00.000Z","ecs.version":"1.2.0","log.level":"INFO","message":"order 42 placed","process.thread.name":"main","log.logger":"com.example.Orders","order.id":"42","order.total":1250}
+----
+
+A number or a boolean stays a JSON number or boolean; any other value is written as its `toString()`.
+A field whose value is `null` is left out.
+The text output types write the fields after the text, as `{order.id=42, order.total=1250}`, with the `%fields` pattern converter, which a pattern of your own can use too.
+
+Name the fields as the backend expects them, such as the https://www.elastic.co/guide/en/ecs/current/ecs-field-reference.html[Elastic Common Schema]'s `http.request.method` or `event.duration` for `JSON`.
+A field must not have the same name as an existing output field, such as `message`.
+The event would then have two fields with that name.
+The output types write these fields:
+
+[cols="1,4"]
+|===
+| Output type | Fields
+
+| `JSON`
+| `@timestamp`, `ecs.version`, `log.level`, `message`, `process.thread.name`, `log.logger`, `tags`, `trace.id`, `span.id`, `log.origin.file.name`, `log.origin.file.line`, `log.origin.function`, `error.type`, `error.message`, `error.stack_trace`, and the logging context's keys
+
+| `GCLOUD`
+| `timestampSeconds`, `timestampNanos`, `severity`, `message`, `logging.googleapis.com/labels`, `logging.googleapis.com/sourceLocation`, `logging.googleapis.com/trace`, `logging.googleapis.com/spanId`, `logging.googleapis.com/trace_sampled`, `exception`, `thread`, `logger`
+|===
+
+The JSON output types write the entries of any of Log4j's map messages this way, such as a `StringMapMessage`.
+
+Fields belong to one event; for fields that every event logged during a request should carry, such as a request id, put them in Log4j's `ThreadContext` instead, with `withLoggingContext` from Log4j's Kotlin API.
+`JSON` writes the context's entries as top-level fields too.
+
[#output-types]
== Output types
@@ -51,10 +93,10 @@ A library that logs through SLF4J or `java.util.logging` logs through Log4j2 too
| The same text, without colours.
| `JSON`
-| One JSON object for each event, in Log4j's JSON template layout's default, Elastic Common Schema, layout.
+| One JSON object for each event, in the https://www.elastic.co/guide/en/ecs/current/index.html[Elastic Common Schema]: the logging context's entries, and the <>, as top-level fields, and the trace and span from the logging context's `trace_id` and `span_id` as ECS's `trace.id` and `span.id`.
| `GCLOUD`
-| One JSON object for each event, in the layout Google Cloud Logging reads as structured logs: the severity in Google Cloud's levels, and the trace and span from the logging context's `trace_id` and `span_id`, so Cloud Logging links each event to its trace.
+| One JSON object for each event, in the layout Google Cloud Logging reads as structured logs: the severity in Google Cloud's levels, the trace and span from the logging context's `trace_id` and `span_id`, so Cloud Logging links each event to its trace, and the <> as top-level fields, which Cloud Logging puts in the entry's `jsonPayload`.
| `EMPTY`
| Nothing: every event is discarded.
@@ -96,7 +138,7 @@ The output types read these environment variables, or the system properties afte
| `LOGGING_LOCATION_ENABLED`
| `logging.location.enabled`
| `false`
-| Whether `JSON` and `GCLOUD` record each event's source location, its class, method, and line, which is costly.
+| Whether `JSON` and `GCLOUD` record each event's source location, its file, method, and line, which is costly.
| `LOGGING_CONSOLE_DIRECT`
| `logging.console.direct`
@@ -174,5 +216,7 @@ LOGGING_TYPE=json ./gradlew :examples:wiring-vanilla:run
* kdoc:boot-logging-log4j2:com.github.rocketraman.bootable.logging.log4j2.LoggingType[]: the output types
* kdoc:boot-logging-log4j2:com.github.rocketraman.bootable.logging.log4j2.loggingInit[]: initializes logging, as `boot { }` does
+* kdoc:boot-logging-log4j2:com.github.rocketraman.bootable.logging.log4j2.StructuredMessage[]: a message with structured fields
* kdoc:boot-logging:com.github.rocketraman.bootable.logging.BootLoggingLevel[]: the log levels
* https://logging.apache.org/log4j/2.x/manual/configuration.html[Log4j2's configuration]
+* https://www.elastic.co/guide/en/ecs/current/ecs-field-reference.html[Elastic Common Schema's fields]
diff --git a/docs/modules/telemetry/pages/index.adoc b/docs/modules/telemetry/pages/index.adoc
index e0177935..d473458f 100644
--- a/docs/modules/telemetry/pages/index.adoc
+++ b/docs/modules/telemetry/pages/index.adoc
@@ -186,7 +186,7 @@ include::ROOT:example$vanilla/telemetry/Spans.kt[tag=root-span]
`Sample.Always` samples the trace whatever `sampleRatio` is, for a trace too rare or too valuable to lose; the default, `Sample.BySampler`, leaves it to the sampler.
-Log events within a span carry its `trace_id` and `span_id`, which xref:logging:index.adoc[`boot-logging-log4j2`]'s layouts print, so a backend can link them to their traces.
+Log events within a span carry its `trace_id` and `span_id` in the logging context, which xref:logging:index.adoc[`boot-logging-log4j2`]'s layouts print, so a backend can link them to their traces: `JSON` writes them as the Elastic Common Schema's `trace.id` and `span.id`, and `GCLOUD` as Cloud Logging's trace and span.
Logs themselves aren't exported over OpenTelemetry: the SDK has no logger provider, so ship them with the platform's log collection.
[#start-tracing]
diff --git a/docs/modules/testing/pages/index.adoc b/docs/modules/testing/pages/index.adoc
index 5a86ca67..7ccab70d 100644
--- a/docs/modules/testing/pages/index.adoc
+++ b/docs/modules/testing/pages/index.adoc
@@ -80,7 +80,7 @@ The result is a `LogCapture`, closed, with these to assert on:
* `describe()`: what was captured, one event per line, such as for an assertion's message.
Each event is Log4j2's own `LogEvent`, copied, with its level, logger, message, thrown, and context data, such as the trace and span ids that `boot-telemetry-otel` puts there.
-`fields` has the structured fields of a map message, such as a `StringMapMessage`.
+`fields` has the structured fields of a map message, such as a xref:logging:index.adoc#fields[`StructuredMessage`], as strings.
A `LogCapture` captures from when it is created until it is closed, so a test can use it around more than one block.
It captures what the logger's level lets through; a `level` lowers the logger's level while it captures, such as to `Level.DEBUG`, and its other appenders then get those events too:
diff --git a/docs/snippets/vanilla/src/main/kotlin/snippets/logging/Logging.kt b/docs/snippets/vanilla/src/main/kotlin/snippets/logging/Logging.kt
index c550a212..7acf319f 100644
--- a/docs/snippets/vanilla/src/main/kotlin/snippets/logging/Logging.kt
+++ b/docs/snippets/vanilla/src/main/kotlin/snippets/logging/Logging.kt
@@ -3,6 +3,7 @@ package snippets.logging
import com.github.rocketraman.bootable.boot.Bootable
import com.github.rocketraman.bootable.boot.boot
import com.github.rocketraman.bootable.logging.BootLoggingLevel
+import com.github.rocketraman.bootable.logging.log4j2.StructuredMessage
import com.github.rocketraman.bootable.logging.log4j2.LoggingType
import com.github.rocketraman.bootable.logging.log4j2.loggingInit
import org.apache.logging.log4j.kotlin.logger
@@ -31,3 +32,23 @@ fun cliMain() {
// ... the tool's work
}
// end::cli[]
+
+// tag::fields[]
+class Orders {
+ private val log = logger()
+
+ fun place(id: String, total: Long) {
+ // ...
+ log.info(StructuredMessage("order $id placed", "order.id" to id, "order.total" to total))
+ }
+}
+
+// an event of the application's own type, with its fields taken from the type
+class Shipment(val orderId: String, val carrier: String)
+
+class OrderShipped(shipment: Shipment) : StructuredMessage(
+ "order ${shipment.orderId} shipped",
+ "order.id" to shipment.orderId,
+ "order.carrier" to shipment.carrier,
+)
+// end::fields[]