Skip to main content
Redhat Developers  Logo
  • AI

    Get started with AI

    • Red Hat AI
      Accelerate the development and deployment of enterprise AI solutions.
    • AI learning hub
      Explore learning materials and tools, organized by task.
    • AI interactive demos
      Click through scenarios with Red Hat AI, including training LLMs and more.
    • AI/ML learning paths
      Expand your OpenShift AI knowledge using these learning resources.
    • AI quickstarts
      Focused AI use cases designed for fast deployment on Red Hat AI platforms.
    • No-cost AI training
      Foundational Red Hat AI training.

    Featured resources

    • OpenShift AI learning
    • Open source AI for developers
    • AI product application development
    • Open source-powered AI/ML for hybrid cloud
    • AI and Node.js cheat sheet

    Red Hat AI Factory with NVIDIA

    • Red Hat AI Factory with NVIDIA is a co-engineered, enterprise-grade AI solution for building, deploying, and managing AI at scale across hybrid cloud environments.
    • Explore the solution
  • Learn

    Self-guided

    • Documentation
      Find answers, get step-by-step guidance, and learn how to use Red Hat products.
    • Learning paths
      Explore curated walkthroughs for common development tasks.
    • Guided learning
      Receive custom learning paths powered by our AI assistant.
    • See all learning

    Hands-on

    • Developer Sandbox
      Spin up Red Hat's products and technologies without setup or configuration.
    • Interactive labs
      Learn by doing in these hands-on, browser-based experiences.
    • Interactive demos
      Click through product features in these guided tours.

    Browse by topic

    • AI/ML
    • Automation
    • Java
    • Kubernetes
    • Linux
    • See all topics

    Training & certifications

    • Courses and exams
    • Certifications
    • Skills assessments
    • Red Hat Academy
    • Learning subscription
    • Explore training
  • Build

    Get started

    • Red Hat build of Podman Desktop
      A downloadable, local development hub to experiment with our products and builds.
    • Developer Sandbox
      Spin up Red Hat's products and technologies without setup or configuration.

    Download products

    • Access product downloads to start building and testing right away.
    • Red Hat Enterprise Linux
    • Red Hat AI
    • Red Hat OpenShift
    • Red Hat Ansible Automation Platform
    • See all products

    Featured

    • Red Hat build of OpenJDK
    • Red Hat JBoss Enterprise Application Platform
    • Red Hat OpenShift Dev Spaces
    • Red Hat Developer Toolset

    References

    • E-books
    • Documentation
    • Cheat sheets
    • Architecture center
  • Community

    Get involved

    • Events
    • Live AI events
    • Red Hat Summit
    • Red Hat Accelerators
    • Community discussions

    Follow along

    • Articles & blogs
    • Developer newsletter
    • Videos
    • Github

    Get help

    • Customer service
    • Customer support
    • Regional contacts
    • Find a partner

    Join the Red Hat Developer program

    • Download Red Hat products and project builds, access support documentation, learning content, and more.
    • Explore the benefits

Persistent Custom MDC Logging in Apache Camel

May 12, 2016
Mary Cochran
Related topics:
Java
Related products:
Red Hat Fuse

    Logging is an ubiquitous need in any production quality application, and one common scenario is to log the active (logged in) username, or to log the user and order IDs for customer order event details. This is typically done to create an audit trail so that issues can be more easily traced should something go wrong, but there are any number of reasons why you might decide to create a custom log.

    Mapped Diagnostic Contexts (MDCs) in Apache Camel are great for creating custom logging statements, and will easily meet our needs for these use cases.  MDC is offered by both slf4j and log4j, and is also supported by JBoss Logging. (Apache Camel is a part of the Red Hat JBoss Fuse integration platform.)

    In addition, you can use something like GELF to automatically index any MDC, thus allowing them to be easily searched using ElasticSearch (logging configuration is not required for this feature), so there are a few reasons why this might be an appealing solution.

    This article will demonstrate how to set up MDC to perform custom logging.

    Using MDC

    MDC primarily stores a key-value map of contextual data (strings mapping to strings), and the context map key can be added to your logging format (logging.properties, or other logging configuration), like in the following example (orderId is the context key):

    %d{HH:mm:ss,SSS} %-5p [%c] %X{camel.routeId} | %X{orderId} | (%t) %s%E%n

    Adding an MDC in Java is as simple as :

    MDC.put("myKey", "myValue");

    With JBoss logging MDCs persist until you remove them.  However, due to a bug, this is not the case for Apache Camel on Karaf. Camel itself does provide some persistent MDCs by default, and these can be found here http://camel.apache.org/mdc-logging.html.

    Now, what if you want your own custom MDC to persist on Camel/Karaf?  If you have a route that is processing an order, logging the order ID throughout the route flow would be very helpful when troubleshooting issues in production. Unless we can persist the MDC, this isn't going to work.

    Making MDC Persistent

    Luckily, all you need to do to get your custom MDC values to persist is extend Camel's MDCUnitOfWork.  At a minimum you will want your extension to look something like the example below that shows your custom "orderId" MDC.  You can also extend the clear() method, and others if you desire, but the methods below are the basic ones you'd need to get the job done.

    public class CustomUnitOfWork extends MDCUnitOfWork implements UnitOfWork {
      public static final String MDC_ORDERID = "orderId";
      private final String originalOrderId;
    
      public CustomUnitOfWork(Exchange exchange) {
        super(exchange);
        this.originalOrderId = MDC.get(MDC_ORDERID);
      }
    
      @Override
        public UnitOfWork newInstance(Exchange exchange) {
        return new CustomUnitOfWork(exchange);
      }
    
      @Override
        public AsyncCallback beforeProcess(Processor processor, Exchange exchange, AsyncCallback callback) {
        return new MyMDCCallback(callback);
      }
    
      /**
      * * {@link AsyncCallback} which preserves {@link org.slf4j.MDC} when the
      * asynchronous routing engine is being used. * This also includes the
      * default camel MDCs.
      */
      private static final class MyMDCCallback implements AsyncCallback {
        private final AsyncCallback delegate;
        private final String breadcrumbId;
        private final String exchangeId;
        private final String messageId;
        private final String correlationId;
        private final String routeId;
        private final String camelContextId;
        private final String orderId;
    
        private MyMDCCallback(AsyncCallback delegate) {
          this.delegate = delegate;
          this.exchangeId = MDC.get(MDC_EXCHANGE_ID);
          this.messageId = MDC.get(MDC_MESSAGE_ID);
          this.breadcrumbId = MDC.get(MDC_BREADCRUMB_ID);
          this.correlationId = MDC.get(MDC_CORRELATION_ID);
          this.camelContextId = MDC.get(MDC_CAMEL_CONTEXT_ID);
          this.routeId = MDC.get(MDC_ROUTE_ID);
          this.orderId = MDC.get(MDC_ORDERID);
        }
      }
    
      public void done(boolean doneSync) {
        try {
          if (!doneSync) {
            // when done asynchronously then restore information from
            // previous thread
            if (breadcrumbId != null) {
              MDC.put(MDC_BREADCRUMB_ID, breadcrumbId);
            }
            if (orderId != null) {
              MDC.put(MDC_ORDERID, orderId);
            }
            if (exchangeId != null) {
              MDC.put(MDC_EXCHANGE_ID, exchangeId);
            }
            if (messageId != null) {
              MDC.put(MDC_MESSAGE_ID, messageId);
            }
            if (correlationId != null) {
              MDC.put(MDC_CORRELATION_ID, correlationId);
            }
            if (camelContextId != null) {
              MDC.put(MDC_CAMEL_CONTEXT_ID, camelContextId);
            }
          }
          // need to setup the routeId finally
          if (routeId != null) {
            MDC.put(MDC_ROUTE_ID, routeId);
          }
        } finally {
          // muse ensure delegate is invoked
          delegate.done(doneSync);
        }
      }
    
      @Override
      public String toString() {
        return delegate.toString();
      }
    }

    Accessing the MDC

    Now how do we use this? If you are using Spring, getting your CustomUnitOfWork in use is easy. First implement the UnitOfWorkFactory, like below:

    public class CustomUnitOfWorkFactory implements UnitOfWorkFactory {
      @Override
      public UnitOfWork createUnitOfWork(Exchange exchange) {
        return new CustomUnitOfWork(exchange);
      }
    }

    Then create your Spring bean:

     <bean id="unitOfWorkFactory" class="com.redhat.example.CustomUnitOfWorkFactory"/>

    Once this is all in place, you can verify your UnitOfWork is in use for your bundle by checking for a log statement starting with 'Using custom UnitOfWorkFactory:' followed by your class name.

    MDCs will persist in logging throughout the Camel route.  Keep in mind there are some exceptions to this. The use of SEDA, or something else that would normally act as a start of a brand new route, will clear the context for that Route.  Your custom MDCs are set up to be treated the same way as the camel.breadcrumbid (a unique id used for tracking messages across transports,) so you can think of it that way.

    Last updated: January 18, 2023

    Recent Posts

    • Debugging image mode with Red Hat OpenShift 4.20: A practical guide

    • EvalHub: Because "looks good to me" isn't a benchmark

    • SQL Server HA on RHEL: Meet Pacemaker HA Agent v2 (tech preview)

    • Deploy with confidence: Continuous integration and continuous delivery for agentic AI

    • Every layer counts: Defense in depth for AI agents with Red Hat AI

    What’s up next?

     

    Red Hat Developers logo LinkedIn YouTube Twitter Facebook

    Platforms

    • Red Hat AI
    • Red Hat Enterprise Linux
    • Red Hat OpenShift
    • Red Hat Ansible Automation Platform
    • See all products

    Build

    • Developer Sandbox
    • Developer tools
    • Interactive tutorials
    • API catalog

    Quicklinks

    • Learning resources
    • E-books
    • Cheat sheets
    • Blog
    • Events
    • Newsletter

    Communicate

    • About us
    • Contact sales
    • Find a partner
    • Report a website issue
    • Site status dashboard
    • Report a security problem

    RED HAT DEVELOPER

    Build here. Go anywhere.

    We serve the builders. The problem solvers who create careers with code.

    Join us if you’re a developer, software engineer, web designer, front-end designer, UX designer, computer scientist, architect, tester, product manager, project manager or team lead.

    Sign me up

    Red Hat legal and privacy links

    • About Red Hat
    • Jobs
    • Events
    • Locations
    • Contact Red Hat
    • Red Hat Blog
    • Inclusion at Red Hat
    • Cool Stuff Store
    • Red Hat Summit
    © 2026 Red Hat

    Red Hat legal and privacy links

    • Privacy statement
    • Terms of use
    • All policies and guidelines
    • Digital accessibility

    Chat Support

    Please log in with your Red Hat account to access chat support.