Apache Camel metrics with Micrometer

Camel can count and time its own routes, endpoints and steps, and routes can record business metrics of their own, all through Micrometer. This page explains which meters each piece creates and what they really count, then runs each one, from handled errors that count as successes to finding the slow step in a route.

Contents

How Camel reports metrics through Micrometer

Micrometer is a metrics facade: code records counters, timers and gauges in a MeterRegistry, and the registry implementation sends them to a monitoring system such as Prometheus, Datadog or an OTLP collector. The camel-micrometer module (Micrometer 1.17 with Camel 4.23) connects Camel to that registry in two ways:

  • The micrometer component: endpoints such as micrometer:counter:orders.placed that a route sends to, so that the route records business metrics of its own.
  • Automatic instrumentation: a route policy that times every exchange of every route, event notifiers that time each endpoint and count routes, and a message history factory that times every node inside a route.

Each meter has a name and a set of tags. Camel adds a camelContext tag to all its meters, and a routeId tag to route meters, so one dashboard query can show all routes or one route.

The pieces of camel-micrometer
PieceMeters it createsBest for
micrometer: endpointsCounters, timers and summaries you nameBusiness numbers: orders, amounts, items
MicrometerRoutePolicyFactorycamel.route.policy, camel.exchanges.*Throughput, errors and latency per route
MicrometerExchangeEventNotifiercamel.exchange.event.notifier, camel.exchanges.inflightTime spent calling each endpoint
MicrometerRouteEventNotifiercamel.routes.added, camel.routes.runningAlerting when a route stops
MicrometerMessageHistoryFactorycamel.message.historyFinding the slow step inside a route

The first four programs are plain Java with a SimpleMeterRegistry, an in-memory registry that is easy to print, and with Camel's logging turned off. The last one runs Spring Boot 4.1 with Actuator, where the starter wires everything up. Programs that measure time print rounded values or comparisons, because exact durations differ on every run.

Business metrics with the micrometer component

An order route usually needs to count orders by channel, sum the items and amounts, and time the processing. The URI form is micrometer:type:name?options, and option values can be Simple expressions:

Java
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.DistributionSummary;
import io.micrometer.core.instrument.Meter;
import io.micrometer.core.instrument.Timer;
import io.micrometer.core.instrument.simple.SimpleMeterRegistry;
import java.util.Comparator;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import org.apache.camel.CamelContext;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.micrometer.MicrometerConstants;
import org.apache.camel.impl.DefaultCamelContext;
import org.slf4j.LoggerFactory;

public class MeterEndpoints {

    public static void main(String[] args) throws Exception {
        ((Logger) LoggerFactory.getLogger("ROOT")).setLevel(Level.OFF);
        SimpleMeterRegistry registry = new SimpleMeterRegistry();
        CamelContext context = new DefaultCamelContext();
        // the micrometer component looks up a registry bound under this name
        context.getRegistry().bind(MicrometerConstants.METRICS_REGISTRY_NAME, registry);
        context.addRoutes(new RouteBuilder() {
            @Override
            public void configure() {
                from("direct:order")
                        .to("micrometer:timer:orders.processing?action=start")
                        .to("micrometer:counter:orders.placed?tags.channel=${header.channel}")
                        .to("micrometer:counter:orders.items?increment=${header.items}")
                        .to("micrometer:summary:orders.amount?value=${header.amount}")
                        .delay(simple("${header.items}0")) // 10 ms per item
                        .to("micrometer:timer:orders.processing?action=stop");
            }
        });
        context.start();
        ProducerTemplate template = context.createProducerTemplate();
        template.sendBodyAndHeaders("direct:order", null,
                Map.of("channel", "web", "items", 2, "amount", 25.0));
        template.sendBodyAndHeaders("direct:order", null,
                Map.of("channel", "web", "items", 1, "amount", 9.5));
        template.sendBodyAndHeaders("direct:order", null,
                Map.of("channel", "app", "items", 5, "amount", 120.0));
        context.close();

        registry.getMeters().stream()
                .sorted(Comparator.comparing((Meter m) -> m.getId().getName())
                        .thenComparing(m -> m.getId().getTags().toString()))
                .forEach(MeterEndpoints::print);
    }

    static void print(Meter meter) {
        String id = meter.getId().getName() + meter.getId().getTags();
        if (meter instanceof Counter c) {
            System.out.printf("counter %-38s count=%.0f%n", id, c.count());
        } else if (meter instanceof DistributionSummary s) {
            System.out.printf("summary %-38s count=%d total=%.1f max=%.1f%n",
                    id, s.count(), s.totalAmount(), s.max());
        } else if (meter instanceof Timer t) {
            System.out.printf("timer   %-38s count=%d total>=80ms=%b max>=50ms=%b%n",
                    id, t.count(), t.totalTime(TimeUnit.MILLISECONDS) >= 80,
                    t.max(TimeUnit.MILLISECONDS) >= 50);
        }
    }
}
Output
summary orders.amount[tag(camelContext=camel-1)] count=3 total=154.5 max=120.0
counter orders.items[tag(camelContext=camel-1)] count=8
counter orders.placed[tag(camelContext=camel-1), tag(channel=app)] count=1
counter orders.placed[tag(camelContext=camel-1), tag(channel=web)] count=2
timer   orders.processing[tag(camelContext=camel-1)] count=3 total>=80ms=true max>=50ms=true
  • orders.placed became two counters, one per value of the channel tag: 2 for web and 1 for app. A tag whose value comes from a header creates one time series per distinct value, so tag only with values from a small, fixed set. A customer id as a tag would create one series per customer and overload the monitoring system.
  • orders.items used increment=${header.items}, so it grew by 2, 1 and 5 to 8.
  • The summary recorded each amount: 3 values, total 154.5, maximum 120.0. A distribution summary is a timer for values that are not durations.
  • The timer was started and stopped by two endpoints with action=start and action=stop, around a delay of 10 ms per item, so the slowest order took at least 50 ms. The program prints comparisons rather than exact times.
  • Every meter got the tag camelContext=camel-1.

The component finds the registry in the Camel registry under the name metricsRegistry (MicrometerConstants.METRICS_REGISTRY_NAME). Headers such as CamelMetricsCounterIncrement and CamelMetricsName can override the URI values per message.

Route metrics: what counts as failed

The route policy factory adds a policy to every route, and the event notifiers listen to every exchange. Six payments go through one route: four succeed, one throws an exception that onException handles, and one throws an exception that nothing handles. The program prints every meter in the registry:

Java
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.FunctionCounter;
import io.micrometer.core.instrument.Gauge;
import io.micrometer.core.instrument.LongTaskTimer;
import io.micrometer.core.instrument.Meter;
import io.micrometer.core.instrument.Timer;
import io.micrometer.core.instrument.simple.SimpleMeterRegistry;
import java.util.stream.Collectors;
import org.apache.camel.CamelContext;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.micrometer.MicrometerConstants;
import org.apache.camel.component.micrometer.eventnotifier.MicrometerExchangeEventNotifier;
import org.apache.camel.component.micrometer.eventnotifier.MicrometerRouteEventNotifier;
import org.apache.camel.component.micrometer.routepolicy.MicrometerRoutePolicyFactory;
import org.apache.camel.impl.DefaultCamelContext;
import org.slf4j.LoggerFactory;

public class RouteMetrics {

    public static void main(String[] args) throws Exception {
        ((Logger) LoggerFactory.getLogger("ROOT")).setLevel(Level.OFF);
        SimpleMeterRegistry registry = new SimpleMeterRegistry();
        CamelContext context = new DefaultCamelContext();
        context.getRegistry().bind(MicrometerConstants.METRICS_REGISTRY_NAME, registry);
        context.addRoutePolicyFactory(new MicrometerRoutePolicyFactory());
        context.getManagementStrategy().addEventNotifier(new MicrometerExchangeEventNotifier());
        context.getManagementStrategy().addEventNotifier(new MicrometerRouteEventNotifier());
        context.addRoutes(new RouteBuilder() {
            @Override
            public void configure() {
                onException(IllegalStateException.class).handled(true);
                from("direct:payments").routeId("payments")
                        .choice()
                            .when(body().isEqualTo("declined"))
                                .throwException(new IllegalStateException("declined"))
                            .when(body().isEqualTo("fraud"))
                                .throwException(new SecurityException("fraud"))
                        .end()
                        .to("log:paid?level=OFF");
            }
        });
        context.start();
        ProducerTemplate template = context.createProducerTemplate();
        for (String payment : new String[] {"ok", "ok", "ok", "declined", "fraud", "ok"}) {
            try {
                template.sendBody("direct:payments", payment);
            } catch (Exception e) {
                // the fraud payment fails; its metrics are what matter here
            }
        }

        registry.getMeters().stream().map(RouteMetrics::describe).sorted()
                .forEach(System.out::println);
        context.close();
    }

    static String describe(Meter meter) {
        // camelContext=camel-1 and kind are on almost every meter, so they are left out
        String tags = meter.getId().getTags().stream()
                .filter(t -> !t.getKey().equals("camelContext") && !t.getKey().equals("kind"))
                .map(t -> t.getKey() + "=" + t.getValue())
                .collect(Collectors.joining(" "));
        String value = switch (meter) {
            case Timer t -> "timer, count " + t.count();
            case LongTaskTimer t -> "long task timer, active " + t.activeTasks();
            case Counter c -> "counter, " + (long) c.count();
            case FunctionCounter c -> "counter, " + (long) c.count();
            case Gauge g when meter.getId().getName().endsWith("timestamp") -> "gauge, a time";
            case Gauge g -> "gauge, " + (long) g.value();
            default -> meter.getClass().getSimpleName();
        };
        return meter.getId().getName() + " {" + tags + "}: " + value;
    }
}
Output
app.info {camel.context=camel-1 camel.runtime.provider=Spring-Boot camel.runtime.version=4.1.2 camel.version=4.23.0}: gauge, 0
camel.exchange.event.notifier {endpointName=direct://payments eventType=ExchangeCompletedEvent failed=false routeId=payments}: timer, count 5
camel.exchange.event.notifier {endpointName=direct://payments eventType=ExchangeFailedEvent failed=true routeId=payments}: timer, count 1
camel.exchange.event.notifier {endpointName=direct://payments eventType=ExchangeSentEvent failed=false routeId=payments}: timer, count 5
camel.exchange.event.notifier {endpointName=direct://payments eventType=ExchangeSentEvent failed=true routeId=payments}: timer, count 1
camel.exchange.event.notifier {endpointName=log://paid eventType=ExchangeSentEvent failed=false routeId=payments}: timer, count 4
camel.exchanges.external.redeliveries {eventType=context routeId=}: counter, 0
camel.exchanges.external.redeliveries {eventType=route routeId=payments}: counter, 0
camel.exchanges.failed {eventType=context routeId=}: counter, 1
camel.exchanges.failed {eventType=route routeId=payments}: counter, 1
camel.exchanges.failures.handled {eventType=context routeId=}: counter, 1
camel.exchanges.failures.handled {eventType=route routeId=payments}: counter, 1
camel.exchanges.inflight {routeId=payments}: gauge, 0
camel.exchanges.last.timestamp {}: gauge, a time
camel.exchanges.succeeded {eventType=context routeId=}: counter, 5
camel.exchanges.succeeded {eventType=route routeId=payments}: counter, 5
camel.exchanges.total {eventType=context routeId=}: counter, 6
camel.exchanges.total {eventType=route routeId=payments}: counter, 6
camel.route.policy {eventType=context routeId=}: timer, count 6
camel.route.policy {eventType=route routeId=payments}: timer, count 6
camel.routes.added {eventType=RouteEvent}: gauge, 1
camel.routes.reloaded {eventType=RouteEvent}: gauge, 0
camel.routes.running {eventType=RouteEvent}: gauge, 1
  • camel.exchanges.total is 6, camel.exchanges.succeeded 5 and camel.exchanges.failed 1. The declined payment threw an exception, but handled(true) turned it into a success, so it counts as succeeded. camel.exchanges.failures.handled shows it separately, with 1.
  • Each counter exists twice: once with eventType=route and routeId=payments, and once with eventType=context for all routes together.
  • camel.route.policy is a timer with count 6. It gives the latency of the whole route, including failed exchanges.
  • camel.exchange.event.notifier timed each endpoint the route sent to: the log://paid endpoint was reached 4 times, the 4 payments that got past the choice(). The failed tag separates the one exchange that ended in an error.
  • camel.routes.added and camel.routes.running are both 1. An alert on running being lower than added catches a route that stopped.
  • camel.exchanges.inflight was 0 because nothing was running when the program printed it, and app.info carries the Camel version as tags.

An error rate built from camel.exchanges.failed alone misses every failure the route handles itself. Alert on failed plus failures.handled, or on handled failures by type with your own counters, when handled errors still mean something went wrong.

Finding the slow step, and percentiles that do not hide outliers

A route timer says that checkout is slow, not why. The message history factory adds a timer for each node, named by the node's id. This program runs a checkout route twenty times, where one payment provider call in ten takes 400 ms instead of 40 ms, and also gives the route timer service level objective buckets at 200 ms and 400 ms:

Java
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import io.micrometer.core.instrument.Timer;
import io.micrometer.core.instrument.distribution.CountAtBucket;
import io.micrometer.core.instrument.simple.SimpleMeterRegistry;
import java.time.Duration;
import java.util.Comparator;
import java.util.concurrent.TimeUnit;
import org.apache.camel.CamelContext;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.micrometer.MicrometerConstants;
import org.apache.camel.component.micrometer.messagehistory.MicrometerMessageHistoryFactory;
import org.apache.camel.component.micrometer.routepolicy.MicrometerRoutePolicyConfiguration;
import org.apache.camel.component.micrometer.routepolicy.MicrometerRoutePolicyFactory;
import org.apache.camel.impl.DefaultCamelContext;
import org.slf4j.LoggerFactory;

public class NodeTimings {

    public static void main(String[] args) throws Exception {
        ((Logger) LoggerFactory.getLogger("ROOT")).setLevel(Level.OFF);
        SimpleMeterRegistry registry = new SimpleMeterRegistry();
        CamelContext context = new DefaultCamelContext();
        context.getRegistry().bind(MicrometerConstants.METRICS_REGISTRY_NAME, registry);

        // per-node timers: one timer for every processor in every route
        context.setMessageHistory(true);
        context.setMessageHistoryFactory(new MicrometerMessageHistoryFactory());

        // route timers with service level objective buckets at 200 ms and 400 ms
        MicrometerRoutePolicyConfiguration config = new MicrometerRoutePolicyConfiguration();
        config.setTimerInitiator(timer -> timer.serviceLevelObjectives(
                Duration.ofMillis(200), Duration.ofMillis(400)));
        MicrometerRoutePolicyFactory policies = new MicrometerRoutePolicyFactory();
        policies.setPolicyConfiguration(config);
        context.addRoutePolicyFactory(policies);

        context.addRoutes(new RouteBuilder() {
            @Override
            public void configure() {
                from("direct:checkout").routeId("checkout")
                        .setHeader("total", constant(42)).id("validate")
                        .delay(simple("${header.providerDelay}")).id("callPaymentProvider")
                        .delay(20).id("saveOrder");
            }
        });
        context.start();
        ProducerTemplate template = context.createProducerTemplate();
        for (int i = 1; i <= 20; i++) {
            // every tenth payment provider call is slow
            template.sendBodyAndHeader("direct:checkout", "order " + i,
                    "providerDelay", i % 10 == 0 ? 400 : 40);
        }

        System.out.println("camel.message.history, mean per node (rounded to 10 ms):");
        registry.find("camel.message.history").timers().stream()
                .sorted(Comparator.comparingDouble((Timer t) -> -t.mean(TimeUnit.MILLISECONDS)))
                .forEach(t -> System.out.printf("  %-20s count=%d mean=%d ms%n",
                        t.getId().getTag("nodeId"), t.count(),
                        Math.round(t.mean(TimeUnit.MILLISECONDS) / 10) * 10));

        Timer route = registry.find("camel.route.policy").tag("routeId", "checkout").timer();
        System.out.println("camel.route.policy for checkout, " + route.count() + " exchanges:");
        for (CountAtBucket bucket : route.takeSnapshot().histogramCounts()) {
            System.out.printf("  at most %3.0f ms: %.0f exchanges%n",
                    bucket.bucket(TimeUnit.MILLISECONDS), bucket.count());
        }
        context.close();
    }
}
Output
camel.message.history, mean per node (rounded to 10 ms):
  callPaymentProvider  count=20 mean=80 ms
  saveOrder            count=20 mean=20 ms
  validate             count=20 mean=0 ms
camel.route.policy for checkout, 20 exchanges:
  at most 200 ms: 18 exchanges
  at most 400 ms: 18 exchanges
  • camel.message.history has one timer per node, tagged with the nodeId set by .id(...). callPaymentProvider was the slowest step, with a mean of about 80 ms; saveOrder took about 20 ms and validate nearly nothing.
  • The mean of 80 ms describes no real call: 18 calls took about 40 ms and 2 took 400 ms. Averages hide outliers.
  • The buckets show them: 18 of 20 exchanges finished within 200 ms, and the same 18 within 400 ms, so 2 took longer than 400 ms. A monitoring system can compute "share of requests under 400 ms" from these counts across many instances, which averages or per-instance percentiles cannot do.

The buckets came from setTimerInitiator on MicrometerRoutePolicyConfiguration, which receives Micrometer's Timer.Builder, so publishPercentileHistogram() and publishPercentiles(0.95) work there too. Message history costs a timer update for every node of every exchange; it is off by default in Spring Boot (camel.metrics.enable-message-history=false), and node ids from .id(...) are what make its output readable.

Meter names: default and legacy styles

Camel 4 names its meters in Micrometer's dotted style. Earlier Camel versions used names such as CamelExchangesTotal, and a legacy naming strategy keeps them for existing dashboards. This program prints the route policy meters under both strategies, together with the snake_case form that a Prometheus registry derives:

Java
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import io.micrometer.core.instrument.Meter;
import io.micrometer.core.instrument.config.NamingConvention;
import io.micrometer.core.instrument.simple.SimpleMeterRegistry;
import java.util.List;
import java.util.TreeSet;
import org.apache.camel.CamelContext;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.micrometer.MicrometerConstants;
import org.apache.camel.component.micrometer.routepolicy.MicrometerRoutePolicyFactory;
import org.apache.camel.component.micrometer.routepolicy.MicrometerRoutePolicyNamingStrategy;
import org.apache.camel.impl.DefaultCamelContext;
import org.slf4j.LoggerFactory;

public class NamingStyles {

    public static void main(String[] args) throws Exception {
        ((Logger) LoggerFactory.getLogger("ROOT")).setLevel(Level.OFF);
        for (MicrometerRoutePolicyNamingStrategy strategy : List.of(
                MicrometerRoutePolicyNamingStrategy.DEFAULT,
                MicrometerRoutePolicyNamingStrategy.LEGACY)) {
            SimpleMeterRegistry registry = new SimpleMeterRegistry();
            CamelContext context = new DefaultCamelContext();
            context.getRegistry().bind(MicrometerConstants.METRICS_REGISTRY_NAME, registry);
            MicrometerRoutePolicyFactory policies = new MicrometerRoutePolicyFactory();
            policies.setNamingStrategy(strategy);
            context.addRoutePolicyFactory(policies);
            context.addRoutes(new RouteBuilder() {
                @Override
                public void configure() {
                    from("direct:in").routeId("orders").to("log:x?level=OFF");
                }
            });
            context.start();
            context.createProducerTemplate().sendBody("direct:in", "x");

            System.out.println(strategy == MicrometerRoutePolicyNamingStrategy.DEFAULT
                    ? "DEFAULT naming, Micrometer name -> snake_case name:"
                    : "LEGACY naming, Micrometer name -> snake_case name:");
            TreeSet<String> lines = new TreeSet<>();
            for (Meter meter : registry.getMeters()) {
                String name = meter.getId().getName();
                // snake_case is the convention a Prometheus registry starts from
                lines.add("  " + name + " -> "
                        + NamingConvention.snakeCase.name(name, meter.getId().getType()));
            }
            lines.forEach(System.out::println);
            context.close();
        }
    }
}
Output
DEFAULT naming, Micrometer name -> snake_case name:
  app.info -> app_info
  camel.exchanges.external.redeliveries -> camel_exchanges_external_redeliveries
  camel.exchanges.failed -> camel_exchanges_failed
  camel.exchanges.failures.handled -> camel_exchanges_failures_handled
  camel.exchanges.succeeded -> camel_exchanges_succeeded
  camel.exchanges.total -> camel_exchanges_total
  camel.route.policy -> camel_route_policy
LEGACY naming, Micrometer name -> snake_case name:
  CamelExchangesExternalRedeliveries -> CamelExchangesExternalRedeliveries
  CamelExchangesFailed -> CamelExchangesFailed
  CamelExchangesFailuresHandled -> CamelExchangesFailuresHandled
  CamelExchangesSucceeded -> CamelExchangesSucceeded
  CamelExchangesTotal -> CamelExchangesTotal
  CamelRoutePolicy -> CamelRoutePolicy
  app.info -> app_info
  • With the default strategy, camel.exchanges.total becomes camel_exchanges_total in snake_case, which is what dashboards query.
  • The legacy names, such as CamelExchangesTotal, contain no dots, so the naming convention leaves them unchanged.
  • app.info is not a route policy meter, so it kept its dotted name in both runs.

The Prometheus registry also adds suffixes, such as _seconds for timers and _total for counters, as the scrape in the Spring Boot section shows. Pick one style when the first dashboard is built: switching later breaks every query and alert that uses the old names. In Spring Boot the property is camel.metrics.naming-strategy, with the values default and legacy.

Spring Boot and Actuator

With camel-micrometer-starter, Spring Boot's MeterRegistry is used for everything, and the route policy and the exchange and route event notifiers are switched on by default. With Actuator, the meters can be read over HTTP. This program starts the application on a random port with webmvc, actuator, camel-spring-boot-starter and camel-micrometer-starter, sends four payments, and reads three meters from /actuator/metrics:

Java
package demo.camel.metrics;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.Map;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.builder.RouteBuilder;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.server.context.WebServerApplicationContext;
import org.springframework.stereotype.Component;

@SpringBootApplication
public class BootActuator {

    @Component
    static class PaymentRoute extends RouteBuilder {
        @Override
        public void configure() {
            from("direct:payments").routeId("payments")
                    .filter(body().isEqualTo("fraud"))
                        .throwException(new SecurityException("fraud"))
                    .end()
                    .to("micrometer:counter:payments.accepted");
        }
    }

    public static void main(String[] args) throws Exception {
        SpringApplication app = new SpringApplication(BootActuator.class);
        app.setDefaultProperties(Map.of(
                "server.port", "0",
                "management.endpoints.web.exposure.include", "health,metrics",
                "spring.main.banner-mode", "off",
                "logging.level.root", "OFF"));
        try (var context = app.run(args)) {
            ProducerTemplate template = context.getBean(ProducerTemplate.class);
            for (String payment : new String[] {"ok", "ok", "fraud", "ok"}) {
                try {
                    template.sendBody("direct:payments", payment);
                } catch (Exception e) {
                    // counted as a failed exchange
                }
            }
            int port = ((WebServerApplicationContext) context).getWebServer().getPort();
            HttpClient http = HttpClient.newHttpClient();
            for (String path : new String[] {
                "/actuator/metrics/payments.accepted",
                "/actuator/metrics/camel.exchanges.failed?tag=routeId:payments",
                "/actuator/metrics/camel.exchanges.total?tag=routeId:payments"}) {
                HttpResponse<String> response = http.send(HttpRequest.newBuilder(
                        URI.create("http://localhost:" + port + path)).build(),
                        HttpResponse.BodyHandlers.ofString());
                System.out.println("GET " + path + " -> " + response.statusCode());
                String body = response.body();
                System.out.println("  " + body.substring(body.indexOf("\"measurements\""),
                        body.indexOf(']', body.indexOf("\"measurements\"")) + 1));
            }
        }
    }
}
Output
GET /actuator/metrics/payments.accepted -> 200
  "measurements":[{"statistic":"COUNT","value":3.0}]
GET /actuator/metrics/camel.exchanges.failed?tag=routeId:payments -> 200
  "measurements":[{"statistic":"COUNT","value":1.0}]
GET /actuator/metrics/camel.exchanges.total?tag=routeId:payments -> 200
  "measurements":[{"statistic":"COUNT","value":4.0}]
  • The route's own counter, payments.accepted, was 3: the fraud payment threw before reaching it.
  • camel.exchanges.failed for routeId:payments was 1 and camel.exchanges.total 4. The tag= query parameter selects one series out of the route and context series.
  • No registry was bound by hand: the starter found Spring Boot's registry and used it for both the component and the automatic metrics.

For Prometheus, add micrometer-registry-prometheus and expose the prometheus endpoint. Spring Boot then creates a PrometheusMeterRegistry instead of the simple one, and Camel's starter uses it without any further setting. This program is the same application with that registry (1.17.2) on the classpath, management.endpoints.web.exposure.include=health,metrics,prometheus and the context name shop. It reads /actuator/prometheus and prints the samples of the payments route:

Java
package demo.camel.prometheus;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.List;
import java.util.Map;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.builder.RouteBuilder;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.server.context.WebServerApplicationContext;
import org.springframework.stereotype.Component;

@SpringBootApplication
public class BootPrometheus {

    @Component
    static class PaymentRoute extends RouteBuilder {
        @Override
        public void configure() {
            from("direct:payments").routeId("payments")
                    .filter(body().isEqualTo("fraud"))
                        .throwException(new SecurityException("fraud"))
                    .end()
                    .to("micrometer:counter:payments.accepted");
        }
    }

    public static void main(String[] args) throws Exception {
        SpringApplication app = new SpringApplication(BootPrometheus.class);
        app.setDefaultProperties(Map.of(
                "server.port", "0",
                "management.endpoints.web.exposure.include", "health,metrics,prometheus",
                "camel.main.name", "shop",
                "spring.main.banner-mode", "off",
                "logging.level.root", "OFF"));
        try (var context = app.run(args)) {
            ProducerTemplate template = context.getBean(ProducerTemplate.class);
            for (String payment : new String[] {"ok", "ok", "fraud", "ok"}) {
                try {
                    template.sendBody("direct:payments", payment);
                } catch (Exception e) {
                    // counted as a failed exchange
                }
            }
            int port = ((WebServerApplicationContext) context).getWebServer().getPort();
            HttpResponse<String> response = HttpClient.newHttpClient().send(
                    HttpRequest.newBuilder(URI.create("http://localhost:" + port
                            + "/actuator/prometheus")).build(),
                    HttpResponse.BodyHandlers.ofString());
            List<String> lines = response.body().lines().toList();
            System.out.println("GET /actuator/prometheus -> " + response.statusCode() + ", "
                    + response.headers().firstValue("Content-Type").orElse(""));
            System.out.println(lines.size() + " lines, "
                    + lines.stream().filter(l -> l.startsWith("camel_")).count()
                    + " samples of Camel meters");
            // the samples of the payments route, without the HELP lines
            for (String line : lines) {
                if (line.startsWith("payments_accepted") || line.contains("routeId=\"payments\"")
                        && (line.startsWith("camel_exchanges_") || line.startsWith(
                                "camel_route_policy_seconds_count"))) {
                    System.out.println(line);
                }
            }
        }
    }
}
Output
GET /actuator/prometheus -> 200, text/plain;version=0.0.4;charset=utf-8
267 lines, 36 samples of Camel meters
camel_exchanges_total{camelContext="shop",eventType="route",kind="CamelRoute",routeId="payments"} 4.0
camel_exchanges_external_redeliveries_total{camelContext="shop",eventType="route",kind="CamelRoute",routeId="payments"} 0.0
camel_exchanges_failed_total{camelContext="shop",eventType="route",kind="CamelRoute",routeId="payments"} 1.0
camel_exchanges_failures_handled_total{camelContext="shop",eventType="route",kind="CamelRoute",routeId="payments"} 0.0
camel_exchanges_inflight{camelContext="shop",kind="CamelExchangeEvent",routeId="payments"} 0.0
camel_exchanges_succeeded_total{camelContext="shop",eventType="route",kind="CamelRoute",routeId="payments"} 3.0
camel_route_policy_seconds_count{camelContext="shop",eventType="route",kind="CamelRoute",routeId="payments"} 4
payments_accepted_total{camelContext="shop"} 3.0
  • The endpoint answered with the Prometheus text format, version=0.0.4, in 267 lines, of which 36 were samples of Camel meters. The rest are the JVM, process, system, executor, Tomcat and HTTP meters that Spring Boot binds, each with HELP and TYPE lines.
  • The counts match the Actuator output above: 4 exchanges in total, 3 succeeded, 1 failed and 0 handled failures for routeId="payments", and payments_accepted_total 3.
  • Counters got the suffix _total: camel.exchanges.failed became camel_exchanges_failed_total. camel.exchanges.total already ends in total, so it became camel_exchanges_total, not camel_exchanges_total_total.
  • The route policy timer camel.route.policy became a family with the unit in its name; camel_route_policy_seconds_count is 4, one per exchange, and the family also has _sum and _max samples with the times.
  • Every Camel series carries camelContext="shop", from camel.main.name, and route series also carry kind and eventType. camel_exchanges_inflight is a gauge from the exchange event notifier, so its kind is CamelExchangeEvent.
  • The scrape also has each route policy meter with eventType="context" and an empty routeId, for the whole context, because camel.metrics.route-policy-level is all by default. The program leaves those lines out.

A Prometheus query such as rate(camel_exchanges_failed_total{routeId="payments"}[5m]) then gives the failure rate per route. The camel.metrics.* properties control the automatic metrics:

Spring Boot properties for Camel metrics
PropertyDefaultEffect
camel.metrics.enable-route-policytrueRoute timers and exchange counters
camel.metrics.route-policy-levelallroute, context or both
camel.metrics.route-policy-exclude-patternNoneRoute ids to leave out
camel.metrics.enable-exchange-event-notifiertruePer-endpoint timers
camel.metrics.enable-route-event-notifiertrueRoute counts
camel.metrics.enable-message-historyfalsePer-node timers
camel.metrics.naming-strategydefaultDotted or legacy names

Tracing, which follows one message across services, is a separate module, camel-opentelemetry, and is not covered here. See the Spring Boot Actuator page for Actuator itself and Camel with Spring Boot for the starter.

Choosing what to measure

Common questions and the meters that answer them
QuestionMeter
How many orders, by channel?micrometer:counter with a tag from a small fixed set
How much money, how many items?micrometer:summary or a counter with increment
Is a route failing?camel.exchanges.failed plus camel.exchanges.failures.handled
Is a route slow?camel.route.policy with SLO buckets or a percentile histogram
Which endpoint is slow?camel.exchange.event.notifier
Which step inside the route is slow?camel.message.history with node ids
Did a route stop?camel.routes.running against camel.routes.added

The traps to remember are handled exceptions that count as successes, tags with unbounded values, averages that hide slow outliers, and renaming meters after dashboards exist.