apache-camel

Overriding or Intercepting Camel Logging


An existing application uses Camel logging (bog the "log()" DSL, and also the Log component.

We would like to either intercept or override so that every log message also logs out a specific Header value (e.g. x-correlation-id=ABC-123)

What is a good, idiomatic way to achieve this?


Solution

  • Apache Camel supports pluggable LogListener since version 2.19.0. This is pretty powerful, because its method onLog, which is invoked right before logging, have instances of Exchange, CamelLogger and message. You can customize the message there with almost no limitations.

    Implementation of LogListener:

    public class MyLogListener implements LogListener {
        @Override
        public String onLog(Exchange exchange, CamelLogger camelLogger, String message) {
            return String.format("%s: %s", exchange.getIn().getHeader(Exchange.CORRELATION_ID), message);
        }
    }
    

    LogListener registration:

    getContext().addLogListener(new MyLogListener());
    

    If you are using Apache Camel version 2.21.0 and newer, you dont need register it to context, because it is looked up in Registry, so annotating MyLogListener as @Bean is enough.