Loki4j uses a high-performance JSON serialization algorithm that avoids runtime reflection. Because of this, arbitrary objects attached via Logback Key-Value Pairs (KVP) are not automatically serialized into complex JSON structures by default.
To handle complex objects, choose one of these three strategies:
1. Use a custom JsonFieldSerializer (Recommended for performance)
Implement com.github.loki4j.logback.json.JsonFieldSerializer<Object> and register it via the <fieldSerializer> setting in the kvp section. This allows you to use JsonEventWriter to manually build the JSON structure for specific types.
2. Use RawJsonString
If you use a reflection-based library (like Jackson) to pre-serialize your object into a JSON string, wrap that string in com.github.loki4j.logback.json.RawJsonString. The writer will then embed the string directly without escaping. Warning: You are responsible for ensuring the string contains valid JSON.
3. Default writeObjectField() behavior
If you do nothing, JsonEventWriter.writeObjectField() handles types as follows:
String: JSON stringInteger/Long: JSON numberBoolean: JSON booleanIterable: JSON arrayRawJsonString: Raw JSON (no escaping)- Other types: The result of
.toString() is rendered as a JSON string (e.g., "obj":"MyObject@12345").
// Example: Implementing a custom field serializer
public class TestFieldSerializer implements JsonFieldSerializer<Object> {
@Override
public void writeField(JsonEventWriter writer, String fieldName, Object fieldValue) {
if (fieldValue instanceof TestJsonKvData) {
writer.writeCustomField(fieldName, w -> {
var td = (TestJsonKvData)fieldValue;
w.writeBeginObject();
w.writeObjectField("userId", td.userId);
w.writeFieldSeparator();
w.writeObjectField("userName", td.userName);
w.writeFieldSeparator();
w.writeObjectField("sessionId", td.sessionId);
w.writeEndObject();
}
);
} else {
writer.writeObjectField(fieldName, fieldValue);
}
}
}
<message class="com.github.loki4j.logback.JsonLayout">
<kvp>
<fieldSerializer class="io.my.TestFieldSerializer" />
</kvp>
</message>