Apache Camel MDC add field from Body

2019-02-16 03:08发布

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?

3条回答
甜甜的少女心
2楼-- · 2019-02-16 03:37

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

查看更多
不美不萌又怎样
3楼-- · 2019-02-16 03:42

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

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

查看更多
孤傲高冷的网名
4楼-- · 2019-02-16 03:46

we wanted a similar thing from our Camel routes - to log particular properties and headers using MDC. Unfortunately our routes were transacted and the CustomMDCUnitOfWork was not kicking in. We ended up implementing an org.apache.camel.spi.InterceptStrategy in order to add the MDC values. If there is a better way of doing this with transacted routes I would be happy to know..!

查看更多
登录 后发表回答