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?
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With