Skip to content

Commit

Permalink
Slf4j MDC context propagation with null MDC map fixed (helidon-io#2861)
Browse files Browse the repository at this point in the history
Slf4j MDC context propagation with null MDC map fixed

Signed-off-by: David Kral <david.k.kral@oracle.com>
  • Loading branch information
Verdent authored and aseovic committed Apr 26, 2021
1 parent 435054d commit 3754d28
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 3 deletions.
@@ -1,5 +1,5 @@
/*
* Copyright (c) 2020 Oracle and/or its affiliates.
* Copyright (c) 2020, 2021 Oracle and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Expand All @@ -16,6 +16,7 @@
package io.helidon.logging.slf4j;

import java.util.Map;
import java.util.Optional;

import io.helidon.common.context.spi.DataPropagationProvider;

Expand All @@ -29,7 +30,7 @@ public class Slf4jMdcPropagator implements DataPropagationProvider<Map<String, S

@Override
public Map<String, String> data() {
return MDC.getCopyOfContextMap();
return Optional.ofNullable(MDC.getCopyOfContextMap()).orElseGet(Map::of);
}

@Override
Expand Down
31 changes: 30 additions & 1 deletion logging/slf4j/src/test/java/Slf4jMdcTest.java
@@ -1,5 +1,5 @@
/*
* Copyright (c) 2020 Oracle and/or its affiliates.
* Copyright (c) 2020, 2021 Oracle and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Expand All @@ -23,6 +23,7 @@
import io.helidon.common.context.ExecutorException;
import io.helidon.logging.common.HelidonMdc;

import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import org.slf4j.MDC;

Expand All @@ -38,6 +39,11 @@ public class Slf4jMdcTest {
private static final String TEST_KEY = "test";
private static final String TEST_VALUE = "value";

@AfterEach
public void clearMdc() {
HelidonMdc.clear();
}

@Test
public void testMdc() {
HelidonMdc.set(TEST_KEY, TEST_VALUE);
Expand Down Expand Up @@ -65,6 +71,21 @@ public void testThreadPropagation() {
});
}

@Test
public void testThreadPropagationWithEmptyMdc() {
Context context = Context.create();
ExecutorService executor = Contexts.wrap(Executors.newFixedThreadPool(1));

Contexts.runInContext(context, () -> {
try {
Boolean value = executor.submit(new TestEmptyMdc()).get();
assertThat(value, is(true));
} catch (Exception e) {
throw new ExecutorException("failed to execute", e);
}
});
}

private static final class TestCallable implements Callable<String> {

@Override
Expand All @@ -73,4 +94,12 @@ public String call() {
}
}

private static final class TestEmptyMdc implements Callable<Boolean> {

@Override
public Boolean call() {
return MDC.getCopyOfContextMap().isEmpty();
}
}

}

0 comments on commit 3754d28

Please sign in to comment.