I have a Spring boot + sleuth based application. All works as expected. I have for now logs like this:
2017-05-04 17:55:52.226 INFO [alert,692d0eeca479e216,c3c8b680dc29ad02,false] 17292 --- [cTaskExecutor-1] c.k.a.b.s.alert.impl.AlertServiceImpl : Alert state to process: xxx
Now, I want to add custom MDC to my log like the contract reference for example. I want to have logs like this:
2017-05-04 17:55:52.226 INFO [alert,692d0eeca479e216,c3c8b680dc29ad02,false] [CONTRACT_REF] 17292 --- [cTaskExecutor-1] c.k.a.b.s.alert.impl.AlertServiceImpl : Alert state to process: xxx
I tried various things with no success:
- Use the Spring Sleuth Tracer to add a tag;
- Add logging.pattern.level=%5p %mdc to my application.properties file with MDC.put(xxx, xxx)
How can I add custom MDC/tags to my log?
For versions before 2.x, You have to create your own implementation of a SpanLogger
. The easiest way will be to extend the Slf4jSpanLogger
and provide your own code to add / update and remove the entries from MDC context. Then you can change your logging pattern and that way your logs will contain what they need.
I was able to add data to the MDC fairly easily by doing MDC.put("yourCoolKey", "your cool value")
(see MDC.put JavaDoc).
Once you put
the value into the MDC
, you can use the sequence %X{yourCoolKey}
in your logging pattern (in my case, the value of logging.pattern.console
) to print the string "your cool value"
as part of each log statement.
Optionally, you can specify a default value in the pattern string by adding :-<defaultValue>
after the key, such as %X{yourCoolKey:-N/A}
, which will print the string "N/A"
whenever the MDC does not have an entry for "yourCoolKey"
. The default, if not specified, is a blank string (""
)