Video in progress

What does the SLF4J 2 fluent API (`log.atInfo().addKeyValue(...)`) give you, and when is it better than putting context in MDC?

The fluent API attaches key-value pairs to a single log event. They become separate fields in JSON logs, but unlike MDC they don't stay on the thread. MDC fits context shared by the whole request (traceId, userId), while addKeyValue fits data that belongs only to this one event.

📖 Answer

MDC is convenient, but it is thread state: once you set a value, it shows up on all the following lines, and if you forget to clear it, it leaks into another request. For data that belongs to a single line (an amount, a provider response code, an attempt number) that is overkill.

log.atInfo()
   .setMessage("To'lov yakunlandi")
   .addKeyValue("orderId", order.id())
   .addKeyValue("amount", order.amount())
   .addKeyValue("provider", "uzcard")
   .log();

With JSON output (Spring Boot 3.4+ structured logging or logstash-logback-encoder), it looks roughly like this:

{"message":"To'lov yakunlandi","orderId":"991","amount":150000,"provider":"uzcard","traceId":"4bf9..."}

In a text pattern, though, key-values are not shown by default; in Logback you add them with the %kvp converter. That is why the fluent API pays off most together with JSON logs.

What to use when:

  • MDC for context you need from the start of the request to the end: traceId, userId, tenantId. You set it in a filter and remove it in finally;
  • addKeyValue for the details of this particular event. It beats cramming "orderId=" + id into the message text: search works on the field, and the message text stays constant, which makes grouping easy.

Another benefit of the fluent API is lazy arguments: addArgument(() -> expensive()) is only evaluated if the level is enabled. Note that this needs SLF4J 2.x and Logback 1.3+; Spring Boot 3 already brings in both.