StructSchemaRegistry

Finds or builds a StructSchema for a class, reflecting over its fields.

A registry reflects a class the first time it is asked for it, then keeps the result, so every request for the same class returns the same schema. Classes nested in its fields are reflected too, and each becomes a nested struct. Give each logger its own registry, or share one.

What is reflected

A Kotlin class contributes its public properties. A Java class contributes its public fields and its getters, which are public no-argument instance methods named getX, or isX returning a boolean, and the field is named x. A Java record contributes its components. A field that is both a public field and a getter is read from the field.

Each field is named after its property, field, or getter, with these types:

  • Boolean, Byte, Short, Int, Long, Float and Double, and the Java primitives and boxes for them

  • DoubleArray, which needs StructSize to declare its length

  • any other concrete class, as a nested struct

Order

The order is the layout on the wire, so changing it changes the schema:

  • A Kotlin class uses primary constructor order, then any remaining properties alphabetically.

  • A Java record uses component order.

  • Any other class uses alphabetical order, because JVM bytecode doesn't keep declaration order for methods.

StructOrder overrides this for any class. Fields marked StructIgnore are skipped, including computed ones you don't want logged.

Nullable properties, strings, collections, enums, and platform types have no struct encoding and are rejected with an error that names the field. Cyclic nesting is rejected too. For such a type, write a schema by hand with structSchema and register it, or mark the field StructIgnore.

The struct's name is the class's simple name, or the value of StructName on it.

Reading fields by reflection boxes each value, so it suits a few structs logged each loop. For a hot path, use a hand-written schema.

Methods are safe to call from multiple threads.

Constructors

Link copied to clipboard
constructor()

Functions

Link copied to clipboard

Returns the schema for type if it already exists, or null otherwise.

Link copied to clipboard
fun <T : Any> register(type: KClass<T>, schema: StructSchema<T>)

Uses schema for type, both when it is requested directly and when it appears as a field of a reflected class. Use it for a class you can't annotate or that reflection can't handle.

Link copied to clipboard
inline fun <T : Any> schemaOf(): StructSchema<T>

Returns the schema for T. See schemaOf.

fun <T : Any> schemaOf(type: Class<T>): StructSchema<T>

Returns the schema for type. See schemaOf.

Returns the schema for type, registered or reflected.