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 MeterRegistrycamel-micrometer
- The micrometer component: endpoints such as
that a route sends to, so that the route records business metrics of its own.micrometer:counter:orders.placed - 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 camelContextrouteId
| Piece | Meters it creates | Best for |
|---|---|---|
micrometer: | Counters, timers and summaries you name | Business numbers: orders, amounts, items |
MicrometerRoutePolicyFactory | camel.route.policycamel.exchanges.* | Throughput, errors and latency per route |
MicrometerExchangeEventNotifier | camel.exchange.event.notifiercamel.exchanges.inflight | Time spent calling each endpoint |
MicrometerRouteEventNotifier | camel.routes.addedcamel.routes.running | Alerting when a route stops |
MicrometerMessageHistoryFactory | camel.message.history | Finding the slow step inside a route |
The first four programs are plain Java with a SimpleMeterRegistry
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
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);
}
}
}
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
became two counters, one per value of theorders.placed tag: 2 forchannel and 1 forweb . 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.app usedorders.items , so it grew by 2, 1 and 5 to 8.increment=${header.items}- The
recorded each amount: 3 values, total 154.5, maximum 120.0. A distribution summary is a timer for values that are not durations.summary - The timer was started and stopped by two endpoints with
andaction=start , 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.action=stop - Every meter got the tag
.camelContext=camel-1
The component finds the registry in the Camel registry under the name metricsRegistryMicrometerConstants.METRICS_REGISTRY_NAMECamelMetricsCounterIncrementCamelMetricsName
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
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;
}
}
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
is 6,camel.exchanges.total 5 andcamel.exchanges.succeeded 1. Thecamel.exchanges.failed payment threw an exception, butdeclined turned it into a success, so it counts as succeeded.handled(true) shows it separately, with 1.camel.exchanges.failures.handled- Each counter exists twice: once with
andeventType=route , and once withrouteId=payments for all routes together.eventType=context is a timer with count 6. It gives the latency of the whole route, including failed exchanges.camel.route.policy timed each endpoint the route sent to: thecamel.exchange.event.notifier endpoint was reached 4 times, the 4 payments that got past thelog://paid . Thechoice() tag separates the one exchange that ended in an error.failed andcamel.routes.added are both 1. An alert oncamel.routes.running being lower thanrunning catches a route that stopped.added was 0 because nothing was running when the program printed it, andcamel.exchanges.inflight carries the Camel version as tags.app.info
An error rate built from camel.exchanges.failedfailedfailures.handled
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:
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();
}
}
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
has one timer per node, tagged with thecamel.message.history set bynodeId ..id(...) was the slowest step, with a mean of about 80 ms;callPaymentProvider took about 20 ms andsaveOrder nearly nothing.validate- 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 setTimerInitiatorMicrometerRoutePolicyConfigurationTimer.BuilderpublishPercentileHistogram()publishPercentiles(0.95)camel.metrics.enable-message-history=false.id(...)
Meter names: default and legacy styles
Camel 4 names its meters in Micrometer's dotted style. Earlier Camel versions used names such as CamelExchangesTotal
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();
}
}
}
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,
becomescamel.exchanges.total in snake_case, which is what dashboards query.camel_exchanges_total - The legacy names, such as
, contain no dots, so the naming convention leaves them unchanged.CamelExchangesTotal is not a route policy meter, so it kept its dotted name in both runs.app.info
The Prometheus registry also adds suffixes, such as _seconds_totalcamel.metrics.naming-strategydefaultlegacy
Spring Boot and Actuator
With camel-micrometer-starterMeterRegistrywebmvcactuatorcamel-spring-boot-startercamel-micrometer-starter/actuator/metrics
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));
}
}
}
}
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,
, was 3: the fraud payment threw before reaching it.payments.accepted forcamel.exchanges.failed was 1 androuteId:payments 4. Thecamel.exchanges.total query parameter selects one series out of the route and context series.tag=- 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-prometheusprometheusPrometheusMeterRegistrymanagement.endpoints.web.exposure.include=health,metrics,prometheusshop/actuator/prometheuspayments
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);
}
}
}
}
}
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,
, 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 withversion=0.0.4 andHELP lines.TYPE - The counts match the Actuator output above: 4 exchanges in total, 3 succeeded, 1 failed and 0 handled failures for
, androuteId="payments" 3.payments_accepted_total - Counters got the suffix
:_total becamecamel.exchanges.failed .camel_exchanges_failed_total already ends incamel.exchanges.total , so it becametotal , notcamel_exchanges_total .camel_exchanges_total_total - The route policy timer
became a family with the unit in its name;camel.route.policy is 4, one per exchange, and the family also hascamel_route_policy_seconds_count and_sum samples with the times._max - Every Camel series carries
, fromcamelContext="shop" , and route series also carrycamel.main.name andkind .eventType is a gauge from the exchange event notifier, so itscamel_exchanges_inflight iskind .CamelExchangeEvent - The scrape also has each route policy meter with
and an emptyeventType="context" , for the whole context, becauserouteId iscamel.metrics.route-policy-level by default. The program leaves those lines out.all
A Prometheus query such as rate(camel_exchanges_failed_total{routeId="payments"}[5m])camel.metrics.*
| Property | Default | Effect |
|---|---|---|
camel.metrics.enable-route-policy | true | Route timers and exchange counters |
camel.metrics.route-policy-level | all | routecontext |
camel.metrics.route-policy-exclude-pattern | None | Route ids to leave out |
camel.metrics.enable-exchange-event-notifier | true | Per-endpoint timers |
camel.metrics.enable-route-event-notifier | true | Route counts |
camel.metrics.enable-message-history | false | Per-node timers |
camel.metrics.naming-strategy | default | Dotted or legacy names |
Tracing, which follows one message across services, is a separate module, camel-opentelemetry
Choosing what to measure
| Question | Meter |
|---|---|
| How many orders, by channel? | micrometer:counter |
| How much money, how many items? | micrometer:summaryincrement |
| Is a route failing? | camel.exchanges.failedcamel.exchanges.failures.handled |
| Is a route slow? | camel.route.policy |
| Which endpoint is slow? | camel.exchange.event.notifier |
| Which step inside the route is slow? | camel.message.history |
| Did a route stop? | camel.routes.runningcamel.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.