From 2595ee9d856abe8f4f4457108e3625a23c1124ad Mon Sep 17 00:00:00 2001 From: Elizabeth Chatman Date: Mon, 18 Oct 2021 23:31:28 -0700 Subject: [PATCH] Allow subclasses to insert custom fields (#151) Protected method that subclasses can override to insert arbitrary custom fields in the logback encoder closes #147 --- .../main/java/co/elastic/logging/logback/EcsEncoder.java | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/logback-ecs-encoder/src/main/java/co/elastic/logging/logback/EcsEncoder.java b/logback-ecs-encoder/src/main/java/co/elastic/logging/logback/EcsEncoder.java index aa6da1c6..80ecf1e1 100644 --- a/logback-ecs-encoder/src/main/java/co/elastic/logging/logback/EcsEncoder.java +++ b/logback-ecs-encoder/src/main/java/co/elastic/logging/logback/EcsEncoder.java @@ -114,6 +114,8 @@ public byte[] encode(ILoggingEvent event) { EcsJsonSerializer.serializeOrigin(builder, callerData[0]); } } + // Allow subclasses to add custom fields. Calling this before the throwable serialization so we don't need to check for presence/absence of an ending comma. + addCustomFields(event, builder); IThrowableProxy throwableProxy = event.getThrowableProxy(); if (throwableProxy instanceof ThrowableProxy) { EcsJsonSerializer.serializeException(builder, ((ThrowableProxy) throwableProxy).getThrowable(), stackTraceAsArray); @@ -125,6 +127,13 @@ public byte[] encode(ILoggingEvent event) { return builder.toString().getBytes(UTF_8); } + /** + * Subclasses can override this to add custom fields. + * The last character in the StringBuilder will be comma when this is called. + * You must add a comma after each custom field. + */ + protected void addCustomFields(ILoggingEvent event, StringBuilder builder) {} + private void serializeMarkers(ILoggingEvent event, StringBuilder builder) { Marker marker = event.getMarker(); if (includeMarkers && marker != null) {