MDC Logging
Mapped Diagnostic Context (MDC) is a Java logging feature that allows attaching custom contextual information to each log entry.
Most major logging frameworks support MDC, and it’s often used to improve logging and monitoring in Java applications, including Apache Camel.
Limitation:
The main limitation of this technology is the fact that it stores values on a context that is available at thread level. Since Camel is an application that manages multiple thread, when it deals with asynchronous calls, the context propagation may not work correctly.
1. Enable MDC in application.properties
- camel.main.mdcLoggingKeysPattern - Defines which MDC keys to propagate during asynchronous message routing.
2. Configure Logging (log4j2.properties)
status = warn
name = MDCLogging
############################
# Appenders
############################
# Route logs: include correlationid and camel.routeId with ANSI colors
appender.route.type = Console
appender.route.name = ROUTE_APP
appender.route.target = SYSTEM_OUT
appender.route.layout.type = PatternLayout
appender.route.layout.disableAnsi = false
appender.route.layout.pattern = [%d{yyyy-MM-dd HH:mm:ss.SSS} - %highlight{%p{length=3}}{FATAL=bg_red bold, ERROR=red bold, WARN=yellow bold, INFO=green bold, DEBUG=blue bold, TRACE=cyan bold}] [%style{%X{correlationid}}{cyan bold}] [%style{%X{camel.routeId}}{green bold}] %m%n
# Default console
appender.stdout.type = Console
appender.stdout.name = out
appender.stdout.target = SYSTEM_OUT
appender.stdout.layout.type = PatternLayout
appender.stdout.layout.pattern = %style{%d{yyyy-MM-dd HH:mm:ss.SSS}}{Dim} %highlight{%5p} %style{%pid}{Magenta} %style{---}{Dim} %style{[%15.15t]}{Dim} %style{%-40.40c}{Cyan} %style{:}{Dim} %m%n
############################
# Loggers
############################
# Your route logs (use log:route in route)
logger.route.name = route
logger.route.level = info
logger.route.additivity = false
logger.route.appenderRefs = route
logger.route.appenderRef.route.ref = ROUTE_APP
############################
# Root
############################
rootLogger.level = info
rootLogger.appenderRefs = out
rootLogger.appenderRef.out.ref = out
3. Set a Custom MDC Key
In Java
In Camel YAML DSL (Groovy script processor):
- script:
id: script-be41
expression:
groovy:
id: groovy-47e8
expression: >-
org.slf4j.MDC.put("correlationid", "CUSTOM_KEY_VALUE")
4. Use the Custom Logger
Additional Resources Apache Camel MDC Documentation