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
1 change: 1 addition & 0 deletions CHANGELOG.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,7 @@ 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.
* `structuredMessageOf`, in the new `boot-logging-log4j2-serialization`, makes a `StructuredMessage` from a `@Serializable` value.
* `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.

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
package com.github.rocketraman.bootable.logging.log4j2.serialization

import com.github.rocketraman.bootable.logging.log4j2.StructuredMessage
import kotlinx.serialization.SerializationStrategy
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonArray
import kotlinx.serialization.json.JsonElement
import kotlinx.serialization.json.JsonNull
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonPrimitive
import kotlinx.serialization.json.booleanOrNull
import kotlinx.serialization.json.doubleOrNull
import kotlinx.serialization.json.longOrNull
import kotlinx.serialization.serializer

/**
* A [StructuredMessage] with the fields of a `@Serializable` [value].
*
* The value is encoded with [json], and each of its properties becomes a field.
* A nested object's properties become fields too, named with a dot, such as `customer.id` for an `Order`'s
* `customer`'s `id`.
* With a [prefix], each field's name starts with it, such as `order.id` for a prefix of `order`.
* A number or a boolean stays a number or a boolean, a list stays a list, and a `null` is left out.
*
* ```
* @Serializable
* data class Order(val id: String, val total: Long, val customer: Customer)
*
* log.info(structuredMessageOf("order ${order.id} placed", order, prefix = "order"))
* ```
*
* A [value] that isn't encoded as an object, such as a number or a list, is a single field, named [prefix], which it
* then needs.
*/
inline fun <reified T> structuredMessageOf(
message: String,
value: T,
prefix: String? = null,
json: Json = Json,
): StructuredMessage = structuredMessageOf(message, value, serializer<T>(), prefix, json)

/** A [StructuredMessage] with the fields of [value], encoded with [serializer]; see the reified overload. */
fun <T> structuredMessageOf(
message: String,
value: T,
serializer: SerializationStrategy<T>,
prefix: String? = null,
json: Json = Json,
): StructuredMessage {
val element = json.encodeToJsonElement(serializer, value)
val fields = LinkedHashMap<String, Any?>()
if (element is JsonObject) {
flatten(prefix, element, fields)
} else {
requireNotNull(prefix) { "a value that isn't encoded as a JSON object needs a prefix to name its field" }
fields[prefix] = element.toValue()
}
return StructuredMessage(message, fields)
}

private fun flatten(prefix: String?, obj: JsonObject, into: MutableMap<String, Any?>) {
for ((key, element) in obj) {
val name = if (prefix == null) key else "$prefix.$key"
if (element is JsonObject) flatten(name, element, into) else into[name] = element.toValue()
}
}

private fun JsonElement.toValue(): Any? = when (this) {
JsonNull -> null
is JsonPrimitive -> if (isString) content else booleanOrNull ?: longOrNull ?: doubleOrNull ?: content
is JsonArray -> map { it.toValue() }
is JsonObject -> mapValues { (_, element) -> element.toValue() }
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
package com.github.rocketraman.bootable.logging.log4j2.serialization

import com.github.rocketraman.bootable.logging.log4j2.StructuredMessage
import de.infix.testBalloon.framework.core.testSuite
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonArray
import kotlinx.serialization.json.JsonPrimitive
import kotlinx.serialization.json.jsonObject
import org.apache.logging.log4j.Level
import org.apache.logging.log4j.core.Appender
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

@Serializable
private data class Customer(val id: String, val vip: Boolean)

@Serializable
private data class Order(
val id: String,
val total: Long,
val discount: Double,
val customer: Customer,
val items: List<String>,
val note: String? = null,
)

private val order = Order("42", 1250, 0.1, Customer("c-7", vip = true), listOf("book", "pen"))

/** [message] as the `JSON` output type writes it. */
private fun renderJson(message: StructuredMessage) = run {
val source = ConfigurationSource.fromResource("log4j2-base-json.xml", StructuredMessage::class.java.classLoader)
val config = XmlConfiguration(null, source).apply { initialize(); start() }
val layout = config.getAppender<Appender>("Console").layout
val event = Log4jLogEvent.newBuilder().setLoggerName("com.example.Orders").setLevel(Level.INFO)
.setMessage(message).build()
Json.parseToJsonElement(String(layout.toByteArray(event), Charsets.UTF_8)).jsonObject
}

val StructuredMessageOfTest by testSuite {
test("each property is a typed field, a nested object's named with a dot, and a null is left out") {
val message = structuredMessageOf("order 42 placed", order)
assert(message.message == "order 42 placed")
assert(
message.fields == mapOf(
"id" to "42",
"total" to 1250L,
"discount" to 0.1,
"customer.id" to "c-7",
"customer.vip" to true,
"items" to listOf("book", "pen"),
),
)
}

test("a prefix starts each field's name") {
val message = structuredMessageOf("order 42 placed", order, prefix = "order")
assert(message.fields.keys.toList() == listOf(
"order.id", "order.total", "order.discount", "order.customer.id", "order.customer.vip", "order.items",
))
}

test("a value that isn't an object is one field, named by the prefix, which it needs") {
assert(structuredMessageOf("retrying", 3, prefix = "retry.count").fields == mapOf("retry.count" to 3L))
val error = runCatching { structuredMessageOf("retrying", 3) }.exceptionOrNull()
assert(error is IllegalArgumentException)
}

test("JSON writes the fields with their types, and a list as an array") {
val json = renderJson(structuredMessageOf("order 42 placed", order, prefix = "order"))
assert(json["message"] == JsonPrimitive("order 42 placed"))
assert(json["order.total"] == JsonPrimitive(1250))
assert(json["order.discount"] == JsonPrimitive(0.1))
assert(json["order.customer.vip"] == JsonPrimitive(true))
assert(json["order.items"] == JsonArray(listOf(JsonPrimitive("book"), JsonPrimitive("pen"))))
}
}
13 changes: 13 additions & 0 deletions build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ dependencies {
dokka(project(":boot-leader-k8s"))
dokka(project(":boot-logging"))
dokka(project(":boot-logging-log4j2"))
dokka(project(":boot-logging-log4j2-serialization"))
dokka(project(":boot-periodic"))
dokka(project(":boot-scheduler-db"))
dokka(project(":boot-server-http-ktor"))
Expand Down Expand Up @@ -1076,6 +1077,18 @@ project("boot-logging-log4j2") {
}
}

project("boot-logging-log4j2-serialization") {
apply(plugin = "org.jetbrains.kotlin.plugin.serialization")
dependencies {
api(project(":boot-logging-log4j2"))
// the value is encoded to a JsonElement, whose properties become the message's fields
api(rootProject.libs.kotlinx.serialization.json)
// the JSON layout, to check the fields' JSON types
testImplementation(platform(rootProject.libs.log4j.bom))
testImplementation(rootProject.libs.bundles.log4j.impl)
}
}

project("boot-server-http-ktor") {
configureDiVariants()
dependencies {
Expand Down
7 changes: 7 additions & 0 deletions docs/modules.yml
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,13 @@ functions:
- name: boot-logging-log4j2
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: Serializable fields
choice: optional
modules:
- name: boot-logging-log4j2-serialization
extends: boot-logging-log4j2
provides: '`structuredMessageOf`, a `StructuredMessage` from a `@Serializable` value'
page: logging:index.adoc#serializable
- title: Core
choice: implied
note: comes with Log4j2
Expand Down
19 changes: 19 additions & 0 deletions docs/modules/logging/pages/index.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,24 @@ The JSON output types write the entries of any of Log4j's map messages this way,
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.

[#serializable]
==== From a serializable value

`structuredMessageOf`, in `boot-logging-log4j2-serialization`, makes a `StructuredMessage` from a `@Serializable` value, with each of its properties as a field:

install::[boot-logging-log4j2-serialization]

[source,kotlin]
----
include::ROOT:example$vanilla/logging/Logging.kt[tag=serializable]
----

The event has the fields `refund.orderId`, `refund.amount`, and `refund.reason`.
A nested object's properties are fields too, named with a dot: a `customer` property with an `id` is the field `refund.customer.id`.
A list stays a list, which `JSON` writes as an array.
The `prefix` is optional; without it, the fields are named for the properties alone.
The value is encoded with kotlinx.serialization's `Json`, or with a `json` of your own, so `@SerialName` names a field.

[#output-types]
== Output types

Expand Down Expand Up @@ -217,6 +235,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-log4j2-serialization:com.github.rocketraman.bootable.logging.log4j2.serialization.structuredMessageOf[]: a `StructuredMessage` from a serializable value
* 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]
3 changes: 3 additions & 0 deletions docs/snippets/vanilla/build.gradle.kts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
plugins {
kotlin("jvm")
// for the @Serializable value in the logging snippet
kotlin("plugin.serialization")
}

// The snippets, wired by hand: the plain coordinate of each module.
Expand Down Expand Up @@ -33,6 +35,7 @@ dependencies {
implementation(project(":boot-client-http-ktor-java"))
implementation(project(":boot-leader-common"))
implementation(project(":boot-logging-log4j2"))
implementation(project(":boot-logging-log4j2-serialization"))
implementation(project(":boot-test-otel"))
implementation(project(":boot-test"))
}
Expand Down
16 changes: 16 additions & 0 deletions docs/snippets/vanilla/src/main/kotlin/snippets/logging/Logging.kt
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ 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 com.github.rocketraman.bootable.logging.log4j2.serialization.structuredMessageOf
import kotlinx.serialization.Serializable
import org.apache.logging.log4j.kotlin.logger

// tag::boot[]
Expand Down Expand Up @@ -52,3 +54,17 @@ class OrderShipped(shipment: Shipment) : StructuredMessage(
"order.carrier" to shipment.carrier,
)
// end::fields[]

// tag::serializable[]
@Serializable
data class Refund(val orderId: String, val amount: Long, val reason: String)

class Refunds {
private val log = logger()

fun refund(refund: Refund) {
// ...
log.info(structuredMessageOf("order ${refund.orderId} refunded", refund, prefix = "refund"))
}
}
// end::serializable[]
1 change: 1 addition & 0 deletions settings.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ include("boot-leader-common")
include("boot-leader-k8s")
include("boot-logging")
include("boot-logging-log4j2")
include("boot-logging-log4j2-serialization")
include("boot-periodic")
include("boot-scheduler-db")
include("boot-server-grpc")
Expand Down
Loading