Search code examples
javaspring-bootapache-camelspring-camel

Spring Boot and Camel- Log Route Duration


I am migrating an application to use the latest version of Spring Boot. Currently all the camel routes are in XML and I have it running using this approach.

All the routes currently log a message at the end of processing. I was wondering is there a way to detect how long it took a particular route to execute and add to the log message. With this information, we can then create datadog dashboards to show stats on our camel routes

Thanks in advance Damien


Solution

  • public class MyLoggingSentEventNotifer extends EventNotifierSupport {
    
      public void notify(EventObject event) throws Exception {
    
        if (event instanceof ExchangeCompletedEvent) {;
          ExchangeCompletedEvent completedEvent = (ExchangeCompletedEvent) event;
          Exchange exchange = completedEvent.getExchange();
          String routeId = exchange.getFromRouteId();
          Date created = ((ExchangeCompletedEvent) event).getExchange()
                            .getProperty(Exchange.CREATED_TIMESTAMP, Date.class);
          // calculate elapsed time
          Date now = new Date();
          long elapsed = now.getTime() - created.getTime();
          log.info("Took " + elapsed + " millis on the route : " + routeId);
        }
    
     }
    
     public boolean isEnabled(EventObject event) {
            // we only want the sent events
            return event instanceof ExchangeSentEvent;
     }
    
     protected void doStart() throws Exception {
            // noop
     }
    
     protected void doStop() throws Exception {
            // noop
     }
    
    }
    
    context.getManagementStrategy().addEventNotifier(new MyLoggingSentEventNotifer());
    

    Reference

    https://people.apache.org/~dkulp/camel/eventnotifier-to-log-details-about-all-sent-exchanges.html

    Update

    The Exchange.CREATED_TIMESTAMP is no longer stored as exchange property, but you should use the getCreated method on Exchange.