MdcLoggerInterceptor { @AroundInvoke public Object addRequestDataToMdc(final InvocationContext invocationContext) throws Exception { ofNullable(serviceContextNameProvider.getServiceContextName()) .ifPresent(value -> { final String jsonAsString = createObjectBuilder().add(SERVICE_CONTEXT, value).build().toString(); MDC.put(REQUEST_DATA, jsonAsString); }); final Object result = invocationContext.proceed(); MDC.remove(REQUEST_DATA); return result; }  @AroundInvoke Object addRequestDataToMdc(final InvocationContext invocationContext);  }
@Test public void shouldAddServiceContextNameToRequestDataMdcLogging() throws Exception { final InvocationContext invocationContext = mock(InvocationContext.class); when(serviceContextNameProvider.getServiceContextName()).thenReturn("exampleService"); when(invocationContext.proceed()).thenAnswer(invocationOnMock -> { assertThat(MDC.get(REQUEST_DATA), isJson(allOf( withJsonPath("$.serviceContext", equalTo("exampleService")) ))); return null; }); mdcLoggerInterceptor.addRequestDataToMdc(invocationContext); assertThat(MDC.get(REQUEST_DATA), nullValue()); }
@Test public void shouldNotAddServiceContextNameIfNull() throws Exception { final InvocationContext invocationContext = mock(InvocationContext.class); when(serviceContextNameProvider.getServiceContextName()).thenReturn(null); when(invocationContext.proceed()).thenAnswer(invocationOnMock -> { assertThat(MDC.get(REQUEST_DATA), nullValue()); return null; }); mdcLoggerInterceptor.addRequestDataToMdc(invocationContext); assertThat(MDC.get(REQUEST_DATA), nullValue()); }