Skip to main content
Redhat Developers  Logo
  • Products

    Featured

    • Red Hat Enterprise Linux
      Red Hat Enterprise Linux Icon
    • Red Hat OpenShift AI
      Red Hat OpenShift AI
    • Red Hat Enterprise Linux AI
      Linux icon inside of a brain
    • Image mode for Red Hat Enterprise Linux
      RHEL image mode
    • Red Hat OpenShift
      Openshift icon
    • Red Hat Ansible Automation Platform
      Ansible icon
    • Red Hat Developer Hub
      Developer Hub
    • View All Red Hat Products
    • Linux

      • Red Hat Enterprise Linux
      • Image mode for Red Hat Enterprise Linux
      • Red Hat Universal Base Images (UBI)
    • Java runtimes & frameworks

      • JBoss Enterprise Application Platform
      • Red Hat build of OpenJDK
    • Kubernetes

      • Red Hat OpenShift
      • Microsoft Azure Red Hat OpenShift
      • Red Hat OpenShift Virtualization
      • Red Hat OpenShift Lightspeed
    • Integration & App Connectivity

      • Red Hat Build of Apache Camel
      • Red Hat Service Interconnect
      • Red Hat Connectivity Link
    • AI/ML

      • Red Hat OpenShift AI
      • Red Hat Enterprise Linux AI
    • Automation

      • Red Hat Ansible Automation Platform
      • Red Hat Ansible Lightspeed
    • Developer tools

      • Red Hat Trusted Software Supply Chain
      • Podman Desktop
      • Red Hat OpenShift Dev Spaces
    • Developer Sandbox

      Developer Sandbox
      Try Red Hat products and technologies without setup or configuration fees for 30 days with this shared Openshift and Kubernetes cluster.
    • Try at no cost
  • Technologies

    Featured

    • AI/ML
      AI/ML Icon
    • Linux
      Linux Icon
    • Kubernetes
      Cloud icon
    • Automation
      Automation Icon showing arrows moving in a circle around a gear
    • View All Technologies
    • Programming Languages & Frameworks

      • Java
      • Python
      • JavaScript
    • System Design & Architecture

      • Red Hat architecture and design patterns
      • Microservices
      • Event-Driven Architecture
      • Databases
    • Developer Productivity

      • Developer productivity
      • Developer Tools
      • GitOps
    • Secure Development & Architectures

      • Security
      • Secure coding
    • Platform Engineering

      • DevOps
      • DevSecOps
      • Ansible automation for applications and services
    • Automated Data Processing

      • AI/ML
      • Data Science
      • Apache Kafka on Kubernetes
      • View All Technologies
    • Start exploring in the Developer Sandbox for free

      sandbox graphic
      Try Red Hat's products and technologies without setup or configuration.
    • Try at no cost
  • Learn

    Featured

    • Kubernetes & Cloud Native
      Openshift icon
    • Linux
      Rhel icon
    • Automation
      Ansible cloud icon
    • Java
      Java icon
    • AI/ML
      AI/ML Icon
    • View All Learning Resources

    E-Books

    • GitOps Cookbook
    • Podman in Action
    • Kubernetes Operators
    • The Path to GitOps
    • View All E-books

    Cheat Sheets

    • Linux Commands
    • Bash Commands
    • Git
    • systemd Commands
    • View All Cheat Sheets

    Documentation

    • API Catalog
    • Product Documentation
    • Legacy Documentation
    • Red Hat Learning

      Learning image
      Boost your technical skills to expert-level with the help of interactive lessons offered by various Red Hat Learning programs.
    • Explore Red Hat Learning
  • Developer Sandbox

    Developer Sandbox

    • Access Red Hat’s products and technologies without setup or configuration, and start developing quicker than ever before with our new, no-cost sandbox environments.
    • Explore Developer Sandbox

    Featured Developer Sandbox activities

    • Get started with your Developer Sandbox
    • OpenShift virtualization and application modernization using the Developer Sandbox
    • Explore all Developer Sandbox activities

    Ready to start developing apps?

    • Try at no cost
  • Blog
  • Events
  • Videos

Persistent Custom MDC Logging in Apache Camel

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

Share:

    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

    • Alternatives to creating bootc images from scratch

    • How to update OpenStack Services on OpenShift

    • How to integrate vLLM inference into your macOS and iOS apps

    • How Insights events enhance system life cycle management

    • Meet the Red Hat Node.js team at PowerUP 2025

    What’s up next?

     

    Red Hat Developers logo LinkedIn YouTube Twitter Facebook

    Products

    • Red Hat Enterprise Linux
    • Red Hat OpenShift
    • Red Hat Ansible Automation Platform

    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

    Red Hat legal and privacy links

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

    Report a website issue