rawJsonField

fun rawJsonField(key: String, json: String, validJson: Boolean = false): LogField(source)

Constructs a LogField, a key-value pair for adding structured data to logs, with the given pre-serialized JSON value.

This function is made to be used with withLoggingContext, to add fields to all logs within a scope. If you just want to add a field to a single log, you should instead call LogBuilder.rawJsonField on one of Logger's methods (see example on rawJsonField).

By default, this function checks that the given JSON string is actually valid JSON. The reason for this is that giving raw JSON to our log encoder when it is not in fact valid JSON can break our logs. So if the given JSON string is not valid JSON, we escape it as a string. If you are 100% sure that the given JSON string is valid and you want to skip this check, you can set validJson to true.

Example

import dev.hermannm.devlog.getLogger
import dev.hermannm.devlog.rawJsonField
import dev.hermannm.devlog.withLoggingContext

private val log = getLogger()

fun example() {
val eventJson = """{"id":1001,"type":"ORDER_PLACED"}"""

withLoggingContext(rawJsonField("event", eventJson)) {
log.debug { "Started processing event" }
// ...
log.debug { "Finished processing event" }
}
}

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

{"message":"Started processing event","event":{"id":1001,"type":"ORDER_PLACED"},/* ...timestamp etc. */}
{"message":"Finished processing event","event":{"id":1001,"type":"ORDER_PLACED"},/* ...timestamp etc. */}

Parameters

validJson

Set this true if you are 100% sure that json is valid JSON, and you want to save the performance cost of validating it.