How to attach log message to cucumber report via MDC

As you may know by default pretty cucumber reports don’t have informative log messages in the report. In order to achieve this we will use MDC.

What is MDC

Base on documentation of logback MDC is deciphered as Mapped Diagnostic Context. MDC lets the developer place information in a diagnostic context that can be subsequently retrieved by certain logback components. The MDC manages contextual information on a per thread basis. Typically, while starting to service a new client request, the developer will insert pertinent contextual information, such as the client id, client’s IP address, request parameters etc. into the MDC. Logback components, if appropriately configured, will automatically include this information in each log entry.

Let’s start with creating a log helper class that will save scenario names in the logging context.

Creating test log helper class

The scope of TestLogHelper is to use MDC in order to put leg messages under a specific key, in our case the key will be testname.

public class TestLogHelper {

    private static final String TEST_NAME = "testname";

    public static void startTestLogging(String name) {
        MDC.put(TEST_NAME, name);
    }

    public static void stopTestLogging() {
        MDC.remove(TEST_NAME);
    }

    public static String getCurrentLogName() {
        return MDC.get(TEST_NAME) == null ? "test" : MDC.get(TEST_NAME);
    }
}

Link test logger helper with cucumber Scenario starting

In order to link MDC with cucumber specific scenario, we will add a cucumber hook where specific logic is handled.

    @Before(order = -3)
    public void loggerConfiguration(Scenario scenario) {
        String scenarioNameFinal = scenario.getName().replaceAll("\\s+", "-");
        scenarioNameFinal = scenarioNameFinal.concat("-" + LocalTime.now().toSecondOfDay());
        TestLogHelper.startTestLogging(scenarioNameFinal);
        logger.info("Current testname value is : " + TestLogHelper.getCurrentLogName());
    }

After these two steps we will have the following output in the cucumber report:

cucumber report with logs

You can find the implementation of the code under the following repository