-
Notifications
You must be signed in to change notification settings - Fork 34
Description
I've found the Mapped Diagnostic Context (MDC) very useful for logging properties of a request that I need in every log. So far I've only been using the MDC to log simple string values and everything has worked as expected. However, I've recently had the need to log numbers, booleans, and more complex objects such as arrays and collections.
The issue i've had is that regardless of the type of the object in the MDC it's always logged as it's String value. For example the integer 5
will be logged as "5"
rather than 5
and the array new String[]{"Foo", "Bar"}
is logged as "[Ljava.lang.String;@5bc06ee1"
when I would expect ["Foo", "Bar"]
. As the MDC supports storing objects, other than strings, I'd like to suggest the changes toio.quarkiverse.loggingjson.providers.MDCJsonProvider
bellow. If this has already been considered and decided against I would love to know the reasons against it!
import io.quarkiverse.loggingjson.Enabled;
import io.quarkiverse.loggingjson.JsonGenerator;
import io.quarkiverse.loggingjson.JsonProvider;
import io.quarkiverse.loggingjson.config.Config;
import java.io.IOException;
import java.util.Map;
import org.jboss.logmanager.ExtLogRecord;
import org.jboss.logmanager.MDC;
public class MDCJsonProvider implements JsonProvider, Enabled {
private final String fieldName;
private final Config.MDCConfig config;
public MDCJsonProvider(Config.MDCConfig config) {
this.config = config;
if (config.flatFields) {
this.fieldName = null;
} else {
this.fieldName = config.fieldName.orElse("mdc");
}
}
public void writeTo(JsonGenerator generator, ExtLogRecord event) throws IOException {
if (fieldName != null) {
generator.writeObjectFieldStart(fieldName);
}
// instead of calling io.quarkiverse.loggingjson.JsonWritingUtils#writeMapStringFields
// we write MDC values as the objects they are
for (Map.Entry<String, Object> entry : MDC.copyObject().entrySet()) {
generator.writeObjectField(entry.getKey(), entry.getKey());
}
if (fieldName != null) {
generator.writeEndObject();
}
}
public boolean isEnabled() {
return this.config.enabled.orElse(true);
}
}