Skip to content

Commit

Permalink
Suppress Default Values from MDC (#120)
Browse files Browse the repository at this point in the history
The library can add fields from the MDC to each generated log messages.
Certain fields are always created, even if the value is unknown. This changes
avoids those fields in the output. This reduces message size and avoids
unnecessary fields in the target service.
The old behaviour is still available by an extra configuration in the logback.xml
or log4j2.xml.

Signed-off-by: Karsten Schnitter <[email protected]>
  • Loading branch information
KarstenSchnitter authored Dec 3, 2021
1 parent fa5b88d commit ac8e76d
Show file tree
Hide file tree
Showing 16 changed files with 470 additions and 324 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,13 @@
import com.fasterxml.jackson.jr.ob.JSON;
import com.fasterxml.jackson.jr.ob.JSONComposer;
import com.fasterxml.jackson.jr.ob.comp.ObjectComposer;
import com.sap.hcp.cf.logging.common.Defaults;
import com.sap.hcp.cf.logging.common.LogContext;

public class DefaultPropertiesConverter {

private final Set<String> exclusions = new HashSet<String>();
private boolean sendDefaultValues = false;

public DefaultPropertiesConverter() {
}
Expand All @@ -31,6 +33,10 @@ public void setExclusions(List<String> exclusionList) {
}
}

public void setSendDefaultValues(boolean sendDefaultValues) {
this.sendDefaultValues = sendDefaultValues;
}

private static class LoggerHolder {
static final Logger LOG = LoggerFactory.getLogger(LoggerHolder.class.getEnclosingClass());
}
Expand All @@ -46,7 +52,14 @@ public void convert(StringBuilder appendTo, Map<String, String> eventProperties)
ObjectComposer<JSONComposer<String>> oc = JSON.std.composeString().startObject();
for (Entry<String, String> p: properties.entrySet()) {
if (!exclusions.contains(p.getKey())) {
oc.put(p.getKey(), p.getValue());
if (sendDefaultValues) {
oc.put(p.getKey(), p.getValue());
} else {
String defaultValue = getDefaultValue(p.getKey());
if (!defaultValue.equals(p.getValue())) {
oc.put(p.getKey(), p.getValue());
}
}
}
}
String result = oc.end().finish().trim();
Expand All @@ -73,4 +86,9 @@ private Map<String, String> mergeContextMaps(Map<String, String> eventMap) {
}
return result;
}

private String getDefaultValue(String key) {
String defaultValue = LogContext.getDefault(key);
return defaultValue == null ? Defaults.UNKNOWN : defaultValue;
}
}
Loading

0 comments on commit ac8e76d

Please sign in to comment.