From cef6f394d4e9c73113f57e4121d5b19815e7256a Mon Sep 17 00:00:00 2001 From: Jimmy Praet Date: Fri, 10 Nov 2017 15:21:50 +0100 Subject: [PATCH] LOGMGR-182 support for logging complete MDC map When using %X in the log pattern without any key arguments, the complete MDC map is now logged in format {key1=value1, key2=value2}. --- .../logmanager/formatters/Formatters.java | 10 +++++--- .../formatters/PatternFormatterTests.java | 23 +++++++++++++++++++ 2 files changed, 30 insertions(+), 3 deletions(-) diff --git a/src/main/java/org/jboss/logmanager/formatters/Formatters.java b/src/main/java/org/jboss/logmanager/formatters/Formatters.java index 56926254..01e61a18 100644 --- a/src/main/java/org/jboss/logmanager/formatters/Formatters.java +++ b/src/main/java/org/jboss/logmanager/formatters/Formatters.java @@ -1008,9 +1008,13 @@ public static FormatStep mdcFormatStep(final String key, final boolean leftJusti public static FormatStep mdcFormatStep(final String key, final boolean leftJustify, final int minimumWidth, final boolean truncateBeginning, final int maximumWidth) { return new JustifyingFormatStep(leftJustify, minimumWidth, truncateBeginning, maximumWidth) { public void renderRaw(final StringBuilder builder, final ExtLogRecord record) { - final String value = record.getMdc(key); - if (value != null) { - builder.append(value); + if (key == null) { + builder.append(record.getMdcCopy()); + } else { + final String value = record.getMdc(key); + if (value != null) { + builder.append(value); + } } } }; diff --git a/src/test/java/org/jboss/logmanager/formatters/PatternFormatterTests.java b/src/test/java/org/jboss/logmanager/formatters/PatternFormatterTests.java index 987a3a9d..2518fe45 100644 --- a/src/test/java/org/jboss/logmanager/formatters/PatternFormatterTests.java +++ b/src/test/java/org/jboss/logmanager/formatters/PatternFormatterTests.java @@ -20,6 +20,7 @@ package org.jboss.logmanager.formatters; import org.jboss.logmanager.ExtLogRecord; +import org.jboss.logmanager.MDC; import org.jboss.logmanager.NDC; import org.junit.Assert; import org.junit.Test; @@ -113,6 +114,28 @@ public void ndc() throws Exception { Assert.assertEquals("value2.value3", formatter.format(record)); } + @Test + public void mdc() throws Exception { + try { + MDC.put("key1", "value1"); + MDC.put("key2", "value2"); + final ExtLogRecord record = createLogRecord("test"); + + PatternFormatter formatter = new PatternFormatter("%X{key1}"); + Assert.assertEquals("value1", formatter.format(record)); + + formatter = new PatternFormatter("%X{not.found}"); + Assert.assertEquals("", formatter.format(record)); + + formatter = new PatternFormatter("%X"); + String formatted = formatter.format(record); + Assert.assertTrue(formatted.equals("{key1=value1, key2=value2}") + || formatted.equals("{key2=value2, key1=value1}")); + } finally { + MDC.clear(); + } + } + @Test public void threads() throws Exception { final ExtLogRecord record = createLogRecord("test");