LogField

sealed class LogField(source)

A log field is a key-value pair for adding structured data to logs.

When outputting logs as JSON (using e.g. logstash-logback-encoder), this becomes a field in the logged JSON object. That allows you to filter and query on the field in the log analysis tool of your choice, in a more structured manner than if you were to just use string concatenation.

You can add a field to a log by calling LogBuilder.field on one of Logger's methods (see example below). This serializes the value using kotlinx.serialization. Alternatively, if you have a value that is already serialized, you can instead call LogBuilder.rawJsonField.

If you want to attach fields to all logs within a scope, you can use withLoggingContext and pass fields to it with the field/rawJsonField functions.

Finally, you can throw or extend ExceptionWithLogFields to attach structured data to an exception when it's logged.

Example

import dev.hermannm.devlog.getLogger
import kotlinx.serialization.Serializable

private val log = getLogger()

fun example() {
val event = Event(id = 1001, type = EventType.ORDER_PLACED)

log.info {
field("event", event)
"Processing event"
}
}

@Serializable
data class Event(val id: Long, val type: EventType)

enum class EventType {
ORDER_PLACED,
ORDER_UPDATED,
}

This gives the following output (using logstash-logback-encoder):

{
"message": "Processing event",
"event": {
"id": 1001,
"type": "ORDER_PLACED"
},
// ...timestamp etc.
}

Functions

Link copied to clipboard
open operator override fun equals(other: Any?): Boolean

Two log fields are equal if their keys and values are equal.

Link copied to clipboard
open override fun hashCode(): Int

Returns the combined hash code of the key and value for this log field.

Link copied to clipboard
open override fun toString(): String

Returns a string representation of the log field, formatted as ${key}=${value}.