How can I add custom fields or data to SLF4J error logs using MDC (Mapped Diagnostic Context)?

Responsive Ad Header

Question

Grade: Education Subject: Support
How can I add custom fields or data to SLF4J error logs using MDC (Mapped Diagnostic Context)?
Asked by:
94 Viewed 94 Answers

Answer (94)

Best Answer
(387)
Use MDC to add custom data to each log message. Before logging the error, put key-value pairs into the MDC: `MDC.put("userId", userId);` Then, in your logging configuration (e.g., `logback.xml`), include MDC placeholders in the log pattern: `%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - userId: %X{userId} - %msg%n`. The MDC data will be logged with the error message.