Observability in Spring Boot: metrics, traces and correlated logs
Spring Boot instruments an application through Micrometer's Observation API, which turns one description of an operation into metrics and trace spans. This page runs the API directly, builds custom meters, follows a trace across an HTTP call with OpenTelemetry, adds @Observed and baggage to a real endpoint, and reads /actuator/prometheus.
Contents
Metrics, traces and logs: one instrumentation
Observability is the ability to understand what a running system is doing from the data it emits. Three kinds of data do most of the work:
- Metrics: numbers aggregated over time, such as requests per second, the 95th percentile latency or the size of a queue. They are cheap to keep and good for dashboards and alerts.
- Traces: the path of one request through the system, as a tree of timed spans, one per operation, across threads and services. They show where the time of a slow request went.
- Logs: individual events with detail. They become far more useful when each line carries the trace id of the request it belongs to.
Spring uses Micrometer for all three. Since Spring Framework 6 and Spring Boot 3, the central API is the ObservationObservationRegistryRestClientWebClient
| Piece | Library | Added by |
|---|---|---|
| Observation API | micrometer-observation | Every Spring Framework 7 application |
Metrics (MeterRegistry | micrometer-core | spring-boot-starter-actuator |
| Tracing API and OpenTelemetry bridge | micrometer-tracingmicrometer-tracing-bridge-otel | spring-boot-starter-opentelemetry |
| OTLP export of traces and metrics | opentelemetry-exporter-otlpmicrometer-registry-otlp | spring-boot-starter-opentelemetry |
| Prometheus scraping | micrometer-registry-prometheus | Added by hand |
| Brave and Zipkin | micrometer-tracing-bridge-brave | spring-boot-starter-zipkin |
spring-boot-starter-opentelemetrymicrometer-registry-prometheus
The Observation API, shown running
Three orders, the last of which fails, are placed through one observation. Two handlers are registered: one prints each lifecycle callback, as a tracing handler would use them to open and close a span, and Micrometer's DefaultMeterObservationHandler
import io.micrometer.core.instrument.Meter;
import io.micrometer.core.instrument.Timer;
import io.micrometer.core.instrument.observation.DefaultMeterObservationHandler;
import io.micrometer.core.instrument.simple.SimpleMeterRegistry;
import io.micrometer.observation.Observation;
import io.micrometer.observation.ObservationHandler;
import io.micrometer.observation.ObservationRegistry;
import java.util.Comparator;
public class ObservationApi {
/** Prints each lifecycle callback, as a tracing handler would turn them into a span. */
static class PrintingHandler implements ObservationHandler<Observation.Context> {
@Override
public void onStart(Observation.Context context) {
System.out.println(" start " + context.getName()
+ " low=" + context.getLowCardinalityKeyValues());
}
@Override
public void onError(Observation.Context context) {
System.out.println(" error " + context.getError().getMessage());
}
@Override
public void onStop(Observation.Context context) {
System.out.println(" stop " + context.getName()
+ " high=" + context.getHighCardinalityKeyValues());
}
@Override
public boolean supportsContext(Observation.Context context) {
return true;
}
}
static void placeOrder(ObservationRegistry registry, String orderId, boolean fail) {
Observation.createNotStarted("orders.place", registry)
.lowCardinalityKeyValue("channel", "web")
.highCardinalityKeyValue("order.id", orderId)
.observe(() -> {
if (fail) {
throw new IllegalStateException("card declined");
}
});
}
public static void main(String[] args) {
SimpleMeterRegistry meters = new SimpleMeterRegistry();
ObservationRegistry registry = ObservationRegistry.create();
registry.observationConfig()
.observationHandler(new PrintingHandler())
.observationHandler(new DefaultMeterObservationHandler(meters));
System.out.println("Order 1001:");
placeOrder(registry, "1001", false);
System.out.println("Order 1002:");
placeOrder(registry, "1002", false);
System.out.println("Order 1003:");
try {
placeOrder(registry, "1003", true);
} catch (IllegalStateException e) {
System.out.println(" caller caught: " + e.getMessage());
}
System.out.println("Meters created by DefaultMeterObservationHandler:");
meters.getMeters().stream()
.sorted(Comparator.comparing((Meter m) -> m.getId().getName())
.thenComparing(m -> m.getId().getTags().toString()))
.forEach(m -> {
String count = m instanceof Timer t ? " count=" + t.count() : "";
System.out.println(" " + m.getId().getType() + " " + m.getId().getName()
+ " " + m.getId().getTags() + count);
});
System.out.println("Observation.NOOP when the registry has no handlers: "
+ Observation.createNotStarted("x", ObservationRegistry.NOOP).isNoop());
}
}
Order 1001:
start orders.place low=[keyValue(channel=web)]
stop orders.place high=[keyValue(order.id=1001)]
Order 1002:
start orders.place low=[keyValue(channel=web)]
stop orders.place high=[keyValue(order.id=1002)]
Order 1003:
start orders.place low=[keyValue(channel=web)]
error card declined
stop orders.place high=[keyValue(order.id=1003)]
caller caught: card declined
Meters created by DefaultMeterObservationHandler:
TIMER orders.place [tag(channel=web), tag(error=IllegalStateException)] count=1
TIMER orders.place [tag(channel=web), tag(error=none)] count=2
LONG_TASK_TIMER orders.place.active [tag(channel=web)]
Observation.NOOP when the registry has no handlers: true
- Each order called
andonStart ; the failed one also calledonStop with the exception, whichonError then rethrew to the caller.observe - The low-cardinality key
became a tag on the timers. The high-cardinality keychannel=web did not: high-cardinality values belong on spans, where every value is fine, but would create one time series per order in a metrics system.order.id - The meter handler created two timer series named
:orders.place with a count of 2 anderror=none with a count of 1. Failure rates come from that tag for free.error=IllegalStateException - It also created a long task timer,
, which counts observations currently in progress.orders.place.active - With
, or a registry with no handlers, observations do nothing and cost close to nothing, which is why libraries can instrument their code unconditionally.ObservationRegistry.NOOP
In a Spring Boot application you do not build the registry yourself: Spring Boot creates an ObservationRegistryObservation.createNotStarted(...)@Observed
Custom metrics and the cardinality trap
Not everything is an observation. Business counts, queue sizes and value distributions use Micrometer's meters directly. This program registers one of each kind on a SimpleMeterRegistry
import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.DistributionSummary;
import io.micrometer.core.instrument.Gauge;
import io.micrometer.core.instrument.Timer;
import io.micrometer.core.instrument.config.MeterFilter;
import io.micrometer.core.instrument.distribution.ValueAtPercentile;
import io.micrometer.core.instrument.simple.SimpleMeterRegistry;
import java.time.Duration;
import java.util.ArrayDeque;
import java.util.Queue;
import java.util.concurrent.TimeUnit;
public class CustomMeters {
public static void main(String[] args) {
SimpleMeterRegistry registry = new SimpleMeterRegistry();
Counter paid = Counter.builder("orders.completed").tag("method", "card")
.register(registry);
Counter.builder("orders.completed").tag("method", "paypal").register(registry)
.increment(2);
paid.increment(5);
System.out.println("Counter orders.completed card=" + paid.count()
+ ", all methods=" + registry.find("orders.completed").counters().stream()
.mapToDouble(Counter::count).sum());
Queue<String> backlog = new ArrayDeque<>();
Gauge.builder("orders.backlog", backlog, Queue::size).register(registry);
backlog.add("a");
backlog.add("b");
backlog.add("c");
System.out.println("Gauge orders.backlog=" + registry.get("orders.backlog").gauge().value()
+ " (read from the queue at the moment it is asked)");
Timer latency = Timer.builder("payment.latency")
.publishPercentiles(0.5, 0.95)
.register(registry);
for (int ms = 10; ms <= 1000; ms += 10) {
latency.record(Duration.ofMillis(ms));
}
System.out.println("Timer payment.latency count=" + latency.count()
+ " mean=" + latency.mean(TimeUnit.MILLISECONDS) + " ms max="
+ latency.max(TimeUnit.MILLISECONDS) + " ms");
for (ValueAtPercentile p : latency.takeSnapshot().percentileValues()) {
System.out.println(" p" + Math.round(p.percentile() * 100) + " about "
+ Math.round(p.value(TimeUnit.MILLISECONDS) / 10) * 10 + " ms");
}
DistributionSummary size = DistributionSummary.builder("order.items").register(registry);
size.record(1);
size.record(3);
size.record(8);
System.out.println("DistributionSummary order.items count=" + size.count()
+ " total=" + size.totalAmount() + " max=" + size.max());
System.out.println("Cardinality: a tag with the user id");
for (int user = 1; user <= 5000; user++) {
registry.counter("logins", "user", "u" + user).increment();
}
System.out.println(" logins series: " + registry.find("logins").counters().size());
SimpleMeterRegistry guarded = new SimpleMeterRegistry();
guarded.config().meterFilter(MeterFilter.maximumAllowableTags(
"logins", "user", 100, MeterFilter.deny()));
for (int user = 1; user <= 5000; user++) {
guarded.counter("logins", "user", "u" + user).increment();
}
System.out.println(" with maximumAllowableTags(100): "
+ guarded.find("logins").counters().size() + " series");
}
}
Counter orders.completed card=5.0, all methods=7.0
Gauge orders.backlog=3.0 (read from the queue at the moment it is asked)
Timer payment.latency count=100 mean=505.0 ms max=1000.0 ms
p50 about 500 ms
p95 about 970 ms
DistributionSummary order.items count=3 total=12.0 max=8.0
Cardinality: a tag with the user id
logins series: 5000
with maximumAllowableTags(100): 100 series
- Counter: only goes up. The two tags made two series, 5 card and 2 PayPal orders; a query sums them to 7.
- Gauge: reports a current value by calling a function on an object when asked, here the size of a queue, 3. Micrometer holds a weak reference to the object, so keep your own reference or the gauge stops reporting.
- Timer: 100 recordings from 10 ms to 1000 ms gave a mean of 505 ms and a maximum of 1000 ms.
computed an approximate p50 of about 500 ms and p95 of about 970 ms in the application.publishPercentiles - DistributionSummary: the same idea for values that are not times, here items per order: 3 orders, 12 items, at most 8.
- A
tag onuser created 5000 series for 5000 users. Each series costs memory in the application and storage in the monitoring system, and a million users would break both.logins capped the tag at 100 values and denied the rest. That is a safety net; the fix is to leave unbounded values out of tags.MeterFilter.maximumAllowableTags
Percentiles computed in the application cannot be combined across instances: the average of ten p95 values is not the p95 of the whole service. For a service with several instances, publish a histogram with publishPercentileHistogram()
Distributed tracing across an HTTP call
A checkout endpoint calls an inventory endpoint over HTTP, which is the shortest way to see a trace cross a process boundary. Both run in the same application here, and a SpanExporter
package observability.tracing;
import io.opentelemetry.sdk.common.CompletableResultCode;
import io.opentelemetry.sdk.trace.SdkTracerProvider;
import io.opentelemetry.sdk.trace.data.SpanData;
import io.opentelemetry.sdk.trace.export.SpanExporter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.server.context.WebServerApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestClient;
@SpringBootApplication
public class TracingAcrossCalls {
/** Collects finished spans in memory instead of sending them to a tracing backend. */
static class CollectingExporter implements SpanExporter {
final List<SpanData> spans = new ArrayList<>();
@Override
public synchronized CompletableResultCode export(Collection<SpanData> batch) {
spans.addAll(batch);
return CompletableResultCode.ofSuccess();
}
@Override
public CompletableResultCode flush() {
return CompletableResultCode.ofSuccess();
}
@Override
public CompletableResultCode shutdown() {
return CompletableResultCode.ofSuccess();
}
}
@Bean
CollectingExporter collectingExporter() {
return new CollectingExporter();
}
@RestController
static class ShopController {
private static final Logger log = LoggerFactory.getLogger(ShopController.class);
private final RestClient restClient;
private final Environment environment;
ShopController(RestClient.Builder builder, Environment environment) {
this.restClient = builder.build();
this.environment = environment;
}
@GetMapping("/checkout")
String checkout() {
log.info("checkout started");
String stock = restClient.get()
.uri("http://localhost:{port}/inventory",
environment.getProperty("local.server.port"))
.retrieve()
.body(String.class);
return "checkout ok, " + stock;
}
@GetMapping("/inventory")
String inventory(@RequestHeader("traceparent") String traceparent) {
log.info("inventory called, traceparent has {} parts", traceparent.split("-").length);
return "3 in stock";
}
}
public static void main(String[] args) throws Exception {
SpringApplication app = new SpringApplication(TracingAcrossCalls.class);
app.setDefaultProperties(Map.of(
"server.port", "0",
"spring.main.banner-mode", "off",
"spring.application.name", "shop",
"logging.level.root", "WARN",
"spring.main.log-startup-info", "false",
"logging.level.observability", "INFO",
"logging.pattern.console", " log: [%X{traceId:-}] %logger{0} - %m%n",
"management.tracing.sampling.probability", "1.0",
"management.tracing.export.otlp.enabled", "false",
"management.otlp.metrics.export.enabled", "false"));
try (var context = app.run(args)) {
int port = ((WebServerApplicationContext) context).getWebServer().getPort();
String body = RestClient.create().get().uri("http://localhost:" + port + "/checkout")
.retrieve().body(String.class);
System.out.println("response: " + body);
context.getBean(SdkTracerProvider.class).forceFlush().join(5, TimeUnit.SECONDS);
List<SpanData> spans = context.getBean(CollectingExporter.class).spans;
Map<String, String> names = new LinkedHashMap<>();
spans.sort((a, b) -> Long.compare(a.getStartEpochNanos(), b.getStartEpochNanos()));
for (SpanData span : spans) {
names.put(span.getSpanId(), span.getName());
}
System.out.println("Spans, in start order:");
for (SpanData span : spans) {
String parent = names.getOrDefault(span.getParentSpanId(), "none");
System.out.println(" " + span.getKind() + " '" + span.getName() + "' parent="
+ parent + " same trace=" + span.getTraceId().equals(
spans.get(0).getTraceId()));
}
}
}
}
log: [e4de2315c12fd6f59e3b76b0634968d5] TracingAcrossCalls$ShopController - checkout started
log: [e4de2315c12fd6f59e3b76b0634968d5] TracingAcrossCalls$ShopController - inventory called, traceparent has 4 parts
response: checkout ok, 3 in stock
Spans, in start order:
SERVER 'http get /checkout' parent=none same trace=true
CLIENT 'http get' parent=http get /checkout same trace=true
SERVER 'http get /inventory' parent=http get same trace=true
- Both log lines carry the same trace id, read from the MDC with
. The id is random, so it differs on every run; searching the logs for it finds every line of this one request.%X{traceId} - The inventory endpoint received a
header with 4 parts: version, trace id, parent span id and flags, as defined by the W3C Trace Context standard. Thetraceparent injected from Spring Boot added it, because it is instrumented.RestClient.Builder - Three spans were recorded, all in the same trace: the server span
, its child the client spanhttp get /checkout for the outgoing call, and the inventory server span, whose parent is that client span.http get - Sampling was set to
. The default is1.0 , so only one request in ten would have been traced.0.1
The trace only continues if the outgoing call uses an instrumented client. A RestClientRestClient.create()mainRestClient.BuilderWebClient.Buildermanagement.opentelemetry.tracing.export.otlp.endpointmanagement.otlp.tracing.endpoint
@Observed and baggage
Business operations deserve their own spans and timers, and some request context, such as a tenant, should travel with the trace to every service. This program puts @Observedbaggage
package observability.observed;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.Timer;
import io.micrometer.observation.annotation.Observed;
import io.opentelemetry.sdk.common.CompletableResultCode;
import io.opentelemetry.sdk.trace.SdkTracerProvider;
import io.opentelemetry.sdk.trace.data.SpanData;
import io.opentelemetry.sdk.trace.export.SpanExporter;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.server.context.WebServerApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
public class ObservedAndBaggage {
static class CollectingExporter implements SpanExporter {
final List<SpanData> spans = new ArrayList<>();
@Override
public synchronized CompletableResultCode export(Collection<SpanData> batch) {
spans.addAll(batch);
return CompletableResultCode.ofSuccess();
}
@Override
public CompletableResultCode flush() {
return CompletableResultCode.ofSuccess();
}
@Override
public CompletableResultCode shutdown() {
return CompletableResultCode.ofSuccess();
}
}
@Bean
CollectingExporter collectingExporter() {
return new CollectingExporter();
}
@Service
static class PricingService {
private static final Logger log = LoggerFactory.getLogger(PricingService.class);
@Observed(name = "pricing.quote", contextualName = "quote price",
lowCardinalityKeyValues = {"currency", "EUR"})
public int quote(String sku) {
log.info("quoting {}", sku);
return 1999;
}
}
@RestController
static class PriceController {
private final PricingService pricing;
PriceController(PricingService pricing) {
this.pricing = pricing;
}
@GetMapping("/price")
int price() {
return pricing.quote("BOOK-7");
}
}
public static void main(String[] args) throws Exception {
SpringApplication app = new SpringApplication(ObservedAndBaggage.class);
Map<String, Object> props = new HashMap<>(Map.of(
"server.port", "0",
"spring.main.banner-mode", "off",
"spring.main.log-startup-info", "false",
"logging.level.root", "WARN",
"logging.level.observability", "INFO",
"logging.pattern.console", " log: [tenant=%X{tenant:-none}] %logger{0} - %m%n"));
props.putAll(Map.of(
"management.observations.annotations.enabled", "true",
"management.tracing.sampling.probability", "1.0",
"management.tracing.baggage.remote-fields", "tenant",
"management.tracing.baggage.correlation.fields", "tenant",
"management.tracing.export.otlp.enabled", "false",
"management.otlp.metrics.export.enabled", "false"));
app.setDefaultProperties(props);
try (var context = app.run(args)) {
int port = ((WebServerApplicationContext) context).getWebServer().getPort();
HttpRequest request = HttpRequest.newBuilder(
URI.create("http://localhost:" + port + "/price"))
.header("baggage", "tenant=acme").build();
HttpResponse<String> response = HttpClient.newHttpClient()
.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println("GET /price with header baggage: tenant=acme -> "
+ response.body());
Timer timer = context.getBean(MeterRegistry.class).find("pricing.quote").timer();
System.out.println("timer pricing.quote count=" + timer.count()
+ " tags=" + timer.getId().getTags());
context.getBean(SdkTracerProvider.class).forceFlush().join(5, TimeUnit.SECONDS);
for (SpanData span : context.getBean(CollectingExporter.class).spans) {
Map<String, Object> attributes = new TreeMap<>();
span.getAttributes().forEach((k, v) -> attributes.put(k.getKey(), v));
attributes.keySet().removeIf(k -> !k.equals("currency") && !k.equals("tenant")
&& !k.equals("method") && !k.equals("class"));
System.out.println("span '" + span.getName() + "' " + attributes);
}
}
}
}
log: [tenant=acme] ObservedAndBaggage$PricingService - quoting BOOK-7
GET /price with header baggage: tenant=acme -> 1999
timer pricing.quote count=1 tags=[tag(class=observability.observed.ObservedAndBaggage$PricingService), tag(currency=EUR), tag(error=none), tag(method=quote)]
span 'quote price' {class=observability.observed.ObservedAndBaggage$PricingService, currency=EUR, method=quote}
span 'http get /price' {method=GET}
produced a timer named@Observed(name = "pricing.quote") with tags for the class, the method,pricing.quote and the extra key-valueerror=none .currency=EUR- The same observation produced a span named after
,contextualName , with the same attributes, as a child of the HTTP server spanquote price .http get /price - The incoming
header was read becausebaggage: tenant=acme is listed intenant , and copied into the MDC bymanagement.tracing.baggage.remote-fields , so the service's log line showscorrelation.fields . An instrumented client would forward the same header to the next service.tenant=acme
@Observedmanagement.observations.annotations.enabled=truefalsespring-boot-starter-aspectjthis
Getting the data out: Prometheus and OTLP
The data has to reach a system that stores and queries it. There are two common models. The Prometheus side, the application serving its metrics as text, runs below; the Prometheus server that scrapes it and the OTLP collector are outside the application and were not run:
- Pull with Prometheus: add
, expose the endpoint withio.micrometer:micrometer-registry-prometheus , and point Prometheus atmanagement.endpoints.web.exposure.include=health,prometheus . Meter names are converted to Prometheus style, so/actuator/prometheus becomesorders.completed .orders_completed_total - Push with OTLP:
brings the OTLP registry. Setspring-boot-starter-opentelemetry to the collector's metrics endpoint; metrics are pushed everymanagement.otlp.metrics.export.url , 1 minute by default.management.otlp.metrics.export.step
What Prometheus reads is plain text. PrometheusMeterRegistrymicrometer-registry-prometheusscrape()
import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.Gauge;
import io.micrometer.core.instrument.Timer;
import io.micrometer.prometheusmetrics.PrometheusConfig;
import io.micrometer.prometheusmetrics.PrometheusMeterRegistry;
import java.time.Duration;
import java.util.ArrayDeque;
import java.util.Queue;
public class PrometheusNaming {
public static void main(String[] args) {
PrometheusMeterRegistry registry = new PrometheusMeterRegistry(PrometheusConfig.DEFAULT);
Counter.builder("orders.completed").description("Orders paid and confirmed")
.tag("method", "card").register(registry).increment(5);
Counter.builder("orders.completed").tag("method", "paypal").register(registry)
.increment(2);
Queue<String> backlog = new ArrayDeque<>();
backlog.add("a");
backlog.add("b");
Gauge.builder("orders.backlog", backlog, Queue::size).register(registry);
Timer latency = Timer.builder("payment.latency")
.serviceLevelObjectives(Duration.ofMillis(100), Duration.ofMillis(500))
.register(registry);
latency.record(Duration.ofMillis(80));
latency.record(Duration.ofMillis(300));
latency.record(Duration.ofMillis(900));
System.out.print(registry.scrape());
}
}
# HELP orders_backlog
# TYPE orders_backlog gauge
orders_backlog 2.0
# HELP orders_completed_total Orders paid and confirmed
# TYPE orders_completed_total counter
orders_completed_total{method="card"} 5.0
orders_completed_total{method="paypal"} 2.0
# HELP payment_latency_seconds
# TYPE payment_latency_seconds histogram
payment_latency_seconds_bucket{le="0.1"} 1
payment_latency_seconds_bucket{le="0.5"} 2
payment_latency_seconds_bucket{le="+Inf"} 3
payment_latency_seconds_count 3
payment_latency_seconds_sum 1.28
# HELP payment_latency_seconds_max
# TYPE payment_latency_seconds_max gauge
payment_latency_seconds_max 0.9
- Dots became underscores, and the counter got the suffix
:_total isorders.completed , one line per tag combination, with the description as itsorders_completed_total text. Meters without a description get an empty# HELP .HELP - The timer is reported in seconds, the Prometheus base unit, as
:payment_latency_seconds 3 and_count 1.28, the total of 0.08, 0.3 and 0.9 seconds. Its maximum became a separate gauge,_sum .payment_latency_seconds_max - The two service level objectives became cumulative histogram buckets: 1 call took at most 0.1 s, 2 at most 0.5 s, and 3 in total (
). Prometheus computes percentiles from buckets withle="+Inf" , across all instances, which client-side percentiles such ashistogram_quantile cannot do.publishPercentiles - The gauge printed 2.0, the size of the queue at the moment of the scrape.
In Spring Boot, adding the registry jar is enough to get a PrometheusMeterRegistry/actuator/prometheus
package observability.prometheus;
import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.MeterRegistry;
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.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.server.context.WebServerApplicationContext;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
public class PrometheusScrape {
@RestController
static class CheckoutController {
private final Counter completed;
CheckoutController(MeterRegistry registry) {
this.completed = Counter.builder("orders.completed").tag("method", "card")
.register(registry);
}
@PostMapping("/checkout")
String checkout() {
completed.increment();
return "paid";
}
}
static HttpResponse<String> send(HttpClient http, HttpRequest request) throws Exception {
return http.send(request, HttpResponse.BodyHandlers.ofString());
}
public static void main(String[] args) throws Exception {
SpringApplication app = new SpringApplication(PrometheusScrape.class);
app.setDefaultProperties(Map.of(
"server.port", "0",
"spring.main.banner-mode", "off",
"logging.level.root", "WARN",
"spring.application.name", "orders",
"management.endpoints.web.exposure.include", "health,prometheus",
"management.observations.key-values.region", "eu-west-1",
"management.tracing.export.otlp.enabled", "false",
"management.otlp.metrics.export.enabled", "false"));
try (var context = app.run(args)) {
int port = ((WebServerApplicationContext) context).getWebServer().getPort();
String base = "http://localhost:" + port;
HttpClient http = HttpClient.newHttpClient();
for (int i = 0; i < 3; i++) {
send(http, HttpRequest.newBuilder(URI.create(base + "/checkout"))
.POST(HttpRequest.BodyPublishers.noBody()).build());
}
HttpResponse<String> text = send(http,
HttpRequest.newBuilder(URI.create(base + "/actuator/prometheus")).build());
System.out.println("GET /actuator/prometheus -> " + text.statusCode() + " "
+ text.headers().firstValue("Content-Type").orElse(""));
text.body().lines()
.filter(l -> l.contains("orders_completed")
|| l.contains("uri=\"/checkout\"") && l.contains("_count"))
.forEach(l -> System.out.println(" " + l));
HttpResponse<String> open = send(http,
HttpRequest.newBuilder(URI.create(base + "/actuator/prometheus"))
.header("Accept", "application/openmetrics-text").build());
System.out.println("Accept: application/openmetrics-text -> "
+ open.headers().firstValue("Content-Type").orElse(""));
open.body().lines().filter(l -> l.contains("orders_completed") || l.equals("# EOF"))
.forEach(l -> System.out.println(" " + l));
}
}
}
GET /actuator/prometheus -> 200 text/plain;version=0.0.4;charset=utf-8
http_server_requests_seconds_count{error="none",exception="none",method="POST",outcome="SUCCESS",region="eu-west-1",status="200",uri="/checkout"} 3
# HELP orders_completed_total
# TYPE orders_completed_total counter
orders_completed_total{method="card"} 3.0
Accept: application/openmetrics-text -> application/openmetrics-text;version=1.0.0;charset=utf-8
# TYPE orders_completed counter
# HELP orders_completed
orders_completed_total{method="card"} 3.0
# EOF
- The endpoint answered with the classic text format,
. Asking fortext/plain;version=0.0.4 returned OpenMetrics 1.0.0, which names the counter familyapplication/openmetrics-text without the suffix and ends withorders_completed .# EOF - The three requests appear as
3 forhttp_server_requests_seconds_count , recorded by Spring MVC's observation, and the custom counter as 3.0.uri="/checkout" , fromregion="eu-west-1" , was added to the HTTP metric, but not tomanagement.observations.key-values.region : the property applies to observations only, and the counter was registered directly on theorders_completed_total . For a tag on every meter, use aMeterRegistry bean.MeterFilter.commonTags- The class is not named
: with that name, its beanPrometheusEndpoint clashed with the actuator endpoint bean of the same name, and the application failed to start with aprometheusEndpoint .BeanDefinitionOverrideException
The push model needs a collector, so these OTLP properties were not run:
spring.application.name=orders
management.tracing.sampling.probability=0.1
management.opentelemetry.tracing.export.otlp.endpoint=http://otel-collector:4318/v1/traces
management.otlp.metrics.export.url=http://otel-collector:4318/v1/metrics
management.observations.key-values.region=eu-west-1
The last line adds region=eu-west-1management.tracing.export.otlp.enabled=falsemanagement.otlp.metrics.export.enabled=falsemetrics
Choosing what to instrument and how
| Need | Use |
|---|---|
| HTTP, database and messaging timings | Nothing: the built-in instrumentation with the actuator starter |
| A business operation as a timer and a span | @ObservedObservation.createNotStarted(...).observe(...) |
| A business count or a current value | CounterGauge |
| Values that are not times, such as sizes | DistributionSummary |
| Following one slow request across services | spring-boot-starter-opentelemetry |
| Finding the logs of one request | The trace id in the log pattern, which Spring Boot adds by default |
| Context such as a tenant on every hop | Baggage with remote-fieldscorrelation.fields |
| Ids, user names or other unbounded values | High-cardinality key-values or span attributes, never metric tags |
| Percentiles across instances | publishPercentileHistogram() |
Start with the instrumentation Spring Boot already provides, add the trace id to the logs, and add @Observed