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 fce8e0f..2a0e45c 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 @@ -29,6 +29,7 @@ import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.classic.spi.IThrowableProxy; import ch.qos.logback.classic.spi.ThrowableProxy; +import ch.qos.logback.core.Layout; import ch.qos.logback.core.encoder.EncoderBase; import co.elastic.logging.AdditionalField; import co.elastic.logging.EcsJsonSerializer; @@ -56,6 +57,7 @@ public class EcsEncoder extends EncoderBase { private boolean includeOrigin; private final List additionalFields = new ArrayList(); private OutputStream os; + protected Layout messageLayout; @Override public byte[] headerBytes() { @@ -105,7 +107,7 @@ public byte[] encode(ILoggingEvent event) { StringBuilder builder = new StringBuilder(256); EcsJsonSerializer.serializeObjectStart(builder, event.getTimeStamp()); EcsJsonSerializer.serializeLogLevel(builder, event.getLevel().toString()); - EcsJsonSerializer.serializeFormattedMessage(builder, event.getFormattedMessage()); + serializeMessage(event, builder); EcsJsonSerializer.serializeEcsVersion(builder); serializeMarkers(event, builder); EcsJsonSerializer.serializeServiceName(builder, serviceName); @@ -140,12 +142,21 @@ public byte[] encode(ILoggingEvent event) { return builder.toString().getBytes(UTF_8); } + private void serializeMessage(ILoggingEvent event, StringBuilder builder) { + if (messageLayout == null) { + EcsJsonSerializer.serializeFormattedMessage(builder, event.getFormattedMessage()); + } else { + EcsJsonSerializer.serializeFormattedMessage(builder, messageLayout.doLayout(event)); + } + } + /** * 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) {} + protected void addCustomFields(ILoggingEvent event, StringBuilder builder) { + } private void serializeMarkers(ILoggingEvent event, StringBuilder builder) { Marker marker = event.getMarker(); @@ -210,4 +221,13 @@ public void setEventDataset(String eventDataset) { public void setThrowableConverter(ThrowableHandlingConverter throwableConverter) { this.throwableConverter = throwableConverter; } + + /** + * The supplied Layout will be applied specifically to format the message field based on the logging event. + * + * @param messageLayout + */ + public void setMessageLayout(Layout messageLayout) { + this.messageLayout = messageLayout; + } }