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
Then, create your custom unit of work class
In your logback/log4j configuration use the value myProp like so:
It should start logging
You can configure a custom
UnitOfWorkFactory
to create a customUnitOfWork
that extends theMDCUnitOfWork
, 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 itwe 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..!