Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apache Camel MDC add field from Body

I am working with apache camel and would like to add certain keys to my logs using MDC. I went through the official Camel MDC Logging documentation which is pretty great. I am able to log my routeId's without much effort. I also need to add a field from Camel's Body.

Worst case scenario I can add this manually in all routes, but I was wondering if its possible to add fields from body to MDC in a easier fashion?

Any ideas are appreciated. I would really like to be able to do this without having to go into every route and adding a one liner.

Update:

Implemented a custom MDCUnitOfWork and Factory in my project. I am able to see the CustomUnitOfWorkFactory creating my CustomUnitOfWork which is then setting the MDC values.

However I noticed this only happens in the beginning of the route.

In my use case, I am Polling an Amazon SQS as my first route. I do not have the required information here. In the first route I build my Context and set that to Camel body which is where my information that I need to set in MDC resides.

Is it possible to create UnitOfWork before second route as well?

like image 637
Rahul Dabas Avatar asked Mar 14 '15 04:03

Rahul Dabas


2 Answers

Here is a full implementation with code based on Claus's recommendation. We are using spring boot, but adjust according to your needs

Auto register a simple bean

@Bean
public CamelContextConfiguration contextConfiguration() {
    return new CamelContextConfiguration() {
        @Override
        public void beforeApplicationStart(CamelContext context) {
            context.setUseMDCLogging(true);
            context.setUnitOfWorkFactory(MyUnitOfWork::new);
        }

        @Override
        public void afterApplicationStart(CamelContext camelContext) {
        }
    };
}

Then, create your custom unit of work class

public class MyUnitOfWork extends MDCUnitOfWork {
    public MyUnitOfWork(Exchange exchange) {
        super(exchange);
        if( exchange.getProperty("myProp") != null){
            MDC.put("myProp", (String) exchange.getProperty("myProp"));
        }
    }
}

In your logback/log4j configuration use the value myProp like so:

%X{myProp}

It should start logging

like image 101
sat Avatar answered Oct 11 '22 12:10

sat


You can configure a custom UnitOfWorkFactory to create a custom UnitOfWork that extends the MDCUnitOfWork, where you can add custom information to MDC.

  • http://camel.apache.org/maven/current/camel-core/apidocs/org/apache/camel/impl/MDCUnitOfWork.html
  • http://camel.apache.org/maven/current/camel-core/apidocs/org/apache/camel/spi/UnitOfWorkFactory.html

You can configure the UnitOfWorkFactory on CamelContext from Java or in XML just add a <bean> and Camel detects and uses it

  • http://camel.apache.org/advanced-configuration-of-camelcontext-using-spring.html
like image 33
Claus Ibsen Avatar answered Oct 11 '22 14:10

Claus Ibsen