Skip to content

Commit

Permalink
Add MDC support in Logback appender
Browse files Browse the repository at this point in the history
  • Loading branch information
dietervdw-spotify committed Feb 12, 2019
1 parent 44db769 commit 522e8a8
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
Expand Down Expand Up @@ -232,6 +233,10 @@ private LogEntry logEntryFor(ILoggingEvent e) {
.addLabel(LEVEL_NAME_KEY, level.toString())
.addLabel(LEVEL_VALUE_KEY, String.valueOf(level.toInt()));

for (Map.Entry<String, String> entry : e.getMDCPropertyMap().entrySet()) {
builder.addLabel(entry.getKey(), entry.getValue());
}

if (loggingEnhancers != null) {
for (LoggingEnhancer enhancer : loggingEnhancers) {
enhancer.enhanceLogEntry(builder);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -181,6 +181,37 @@ public void testDefaultWriteOptionsHasExpectedDefaults() {
// assertThat(resourceArg.getValue()).isEqualTo(defaultWriteOptions[1]);
}

@Test
public void testMdcValuesAreConvertedToLabels() {
LogEntry logEntry =
LogEntry.newBuilder(StringPayload.of("this is a test"))
.setTimestamp(100000L)
.setSeverity(Severity.INFO)
.setLabels(
new ImmutableMap.Builder<String, String>()
.put("levelName", "INFO")
.put("levelValue", String.valueOf(20000L))
.put("mdc1", "value1")
.put("mdc2", "value2")
.build())
.build();
logging.setFlushSeverity(Severity.ERROR);
Capture<Iterable<LogEntry>> capturedArgument = Capture.newInstance();
logging.write(capture(capturedArgument), (WriteOption) anyObject(), (WriteOption) anyObject());
expectLastCall().once();
replay(logging);
Timestamp timestamp = Timestamp.ofTimeSecondsAndNanos(100000, 0);
LoggingEvent loggingEvent = createLoggingEvent(Level.INFO, timestamp.getSeconds());
loggingEvent
.setMDCPropertyMap(ImmutableMap.of("mdc1", "value1", "mdc2", "value2"));
loggingAppender.start();
// info event does not get logged
loggingAppender.doAppend(loggingEvent);
verify(logging);
assertThat(capturedArgument.getValue().iterator().hasNext()).isTrue();
assertThat(capturedArgument.getValue().iterator().next()).isEqualTo(logEntry);
}

private LoggingEvent createLoggingEvent(Level level, long timestamp) {
LoggingEvent loggingEvent = new LoggingEvent();
loggingEvent.setMessage("this is a test");
Expand Down

0 comments on commit 522e8a8

Please sign in to comment.