Skip to content

Commit 0d03cd0

Browse files
Omit empty JSON field #cf Log4j2 without custom fields
When there are no custom fields defined in the log4j configuration, we never need to generate the #cf field in any log messages. The converter can be removed in this case entirely.
1 parent 916ea89 commit 0d03cd0

File tree

2 files changed

+19
-1
lines changed

2 files changed

+19
-1
lines changed

cf-java-logging-support-log4j2/src/main/java/com/sap/hcp/cf/log4j2/layout/LayoutPatternBuilder.java

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,9 @@ public LayoutPatternBuilder addContextProperties(List<String> exclusions) {
5656
}
5757

5858
public LayoutPatternBuilder addCustomFields(List<String> mdcKeyNames) {
59+
if (mdcKeyNames == null || mdcKeyNames.isEmpty()) {
60+
return this;
61+
}
5962
sb.append("\"").append(Fields.CUSTOM_FIELDS).append("\":");
6063
sb.append("{%").append(CustomFieldsConverter.WORD);
6164
appendParameters(mdcKeyNames);

cf-java-logging-support-log4j2/src/test/java/com/sap/hcp/cf/log4j2/layout/LayoutPatternBuilderTest.java

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,12 @@
22

33
import static java.util.Arrays.asList;
44
import static java.util.Collections.emptyList;
5+
import static org.hamcrest.MatcherAssert.assertThat;
56
import static org.hamcrest.Matchers.is;
67
import static org.hamcrest.Matchers.isEmptyString;
7-
import static org.junit.Assert.assertThat;
88

99
import java.util.Arrays;
10+
import java.util.Collections;
1011

1112
import org.hamcrest.FeatureMatcher;
1213
import org.hamcrest.Matcher;
@@ -54,6 +55,20 @@ public void customFields() throws Exception {
5455
assertThat(pattern, specificPart(is(",\"#cf\":{%cf{this key}{that key}}")));
5556
}
5657

58+
@Test
59+
public void emptyCustomFields() throws Exception {
60+
String pattern = new LayoutPatternBuilder().addCustomFields(Collections.emptyList()).build();
61+
62+
assertThat(pattern, specificPart(is("")));
63+
}
64+
65+
@Test
66+
public void nullCustomFields() throws Exception {
67+
String pattern = new LayoutPatternBuilder().addCustomFields(null).build();
68+
69+
assertThat(pattern, specificPart(is("")));
70+
}
71+
5772
@Test
5873
public void stacktrace() throws Exception {
5974
String pattern = new LayoutPatternBuilder().addStacktraces().build();

0 commit comments

Comments
 (0)