raw Json
Turns the given pre-serialized JSON string into a JsonElement (from kotlinx.serialization
), using the same validation logic as 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. If the JSON is valid, we can use JsonUnquotedLiteral to avoid having to re-encode it when serializing into another object. But if it's not valid JSON, we escape it as a string (returning a JsonPrimitive). 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.
This is useful when you want to include a raw JSON field on a log. If it's a top-level field, you can use rawJsonField - but if you want the field to be in a nested object, then you can use this function.
Example
import dev.hermannm.devlog.getLogger
import dev.hermannm.devlog.rawJson
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.JsonElement
private val log = getLogger()
fun example() {
// We hope the external service returns valid JSON, but we can't trust that fully. If it did
// return JSON, we want to log it unescaped, but if it didn't, we want to log it as a string.
// `rawJson` does this validation for us.
val response = callExternalService()
if (!response.status.isSuccessful()) {
// We want to log a "response" log field with an object of "status" and "body". So we create
// a serializable class with the fields we want, and make "body" a JsonElement from rawJson.
@Serializable data class ResponseLog(val status: Int, val body: JsonElement)
log.error {
field("response", ResponseLog(response.status.code, rawJson(response.body)))
"External service returned error response"
}
}
}
Parameters
Set this true if you are 100% sure that json is valid JSON, and you want to save the performance cost of validating it.