Add custom value to every log message

Viewed 5170

Let's say that I have a REST API with endpoint /user/{user_id}/foo. Now when it is called I would like that all logs that come from handling this request contain information about {user_id}. Is it possible to achieve that without passing {user_id} to every method?

I'm using SLF4j for logging, my application is based on Spring Boot.

2 Answers

You could also use MDC for this, see here. It's essentially a map, you just put your contextual information in it (e.g. user id) and then you can use it in your log layout. Be aware that this only works with certain underlying frameworks like logback, where a sample layout pattern would look like this:

<Pattern>%X{user_id} %m%n</Pattern>

Check the logback manual for more details on this.

You can use Logback's Mapped Diagnotic Context to propagate the {user_id} to every log message.

There are two parts to this:

  • Push your {user_id} into MDC e.g. MDC.put("user_id", "Pawel");

  • Include the MDC entry in your log statements. You do this by specifying it in your logging pattern. So, if you store the user id in a MDC entry named "user_id" the you would set logging.pattern.level=user_id:%X{user_id} %5p to include the value of that entry in every log event.

More details in the docs

Related