field

inline fun <ValueT> field(key: String, value: ValueT): LogField(source)
fun <ValueT : Any> field(key: String, value: ValueT?, serializer: SerializationStrategy<ValueT>): LogField(source)

Constructs a LogField, a key-value pair for adding structured data to logs.

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.field on one of Logger's methods (see example).

The value is serialized using kotlinx.serialization, so if you pass an object here, you should make sure it is annotated with @Serializable. If serialization fails, we fall back to calling toString() on the value.

If you want to specify the serializer for the value explicitly, you can call the overload of this function that takes a SerializationStrategy as a third parameter. That is also useful for cases where you can't call this function with a reified type parameter.

If you have a value that is already serialized, you should use rawJsonField instead.

Special-case handling for common types

Certain types that kotlinx.serialization doesn't support natively have special-case handling here, using their toString() representation instead:

  • java.time.Instant

  • java.util.UUID

  • java.net.URI

  • java.net.URL

  • java.math.BigDecimal