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 Observation: code describes an operation once, with a name and key-values, and handlers registered on an ObservationRegistry turn it into a timer, a span, or both. Spring MVC, WebFlux, RestClient, WebClient, JDBC drivers and messaging clients are already instrumented this way, so a Spring Boot application produces metrics and traces for HTTP calls without any code.

The pieces and where they come from in Spring Boot 4
PieceLibraryAdded by
Observation APImicrometer-observationEvery Spring Framework 7 application
Metrics (MeterRegistry, timers, counters)micrometer-corespring-boot-starter-actuator
Tracing API and OpenTelemetry bridgemicrometer-tracing, micrometer-tracing-bridge-otelspring-boot-starter-opentelemetry
OTLP export of traces and metricsopentelemetry-exporter-otlp, micrometer-registry-otlpspring-boot-starter-opentelemetry
Prometheus scrapingmicrometer-registry-prometheusAdded by hand
Brave and Zipkinmicrometer-tracing-bridge-bravespring-boot-starter-zipkin

spring-boot-starter-opentelemetry is new in Spring Boot 4. In Spring Boot 3 the same setup took the actuator starter plus the bridge and exporter dependencies listed one by one. The first two programs below use Micrometer alone, without Spring; the next two run Spring Boot 4.1.2 with Spring MVC, the actuator and the OpenTelemetry starter. The last two add micrometer-registry-prometheus, first on its own and then in Spring Boot.

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 turns the same observation into timers:

Java
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());
    }
}
Output
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 onStart and onStop; the failed one also called onError with the exception, which observe then rethrew to the caller.
  • The low-cardinality key channel=web became a tag on the timers. The high-cardinality key order.id 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.
  • The meter handler created two timer series named orders.place: error=none with a count of 2 and error=IllegalStateException with a count of 1. Failure rates come from that tag for free.
  • It also created a long task timer, orders.place.active, which counts observations currently in progress.
  • With ObservationRegistry.NOOP, or a registry with no handlers, observations do nothing and cost close to nothing, which is why libraries can instrument their code unconditionally.

In a Spring Boot application you do not build the registry yourself: Spring Boot creates an ObservationRegistry bean and registers the meter handler and, when tracing is present, the tracing handler on it. You inject the registry and call Observation.createNotStarted(...), or use @Observed as shown later.

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, then shows what a user id in a tag does:

Java
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");
    }
}
Output
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. publishPercentiles computed an approximate p50 of about 500 ms and p95 of about 970 ms in the application.
  • DistributionSummary: the same idea for values that are not times, here items per order: 3 orders, 12 items, at most 8.
  • A user tag on logins 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.
  • MeterFilter.maximumAllowableTags 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.

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() and let the monitoring system compute percentiles over all of them.

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 bean collects finished spans in memory instead of sending them to a tracing backend:

Java
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()));
            }
        }
    }
}
Output
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 %X{traceId}. The id is random, so it differs on every run; searching the logs for it finds every line of this one request.
  • The inventory endpoint received a traceparent header with 4 parts: version, trace id, parent span id and flags, as defined by the W3C Trace Context standard. The RestClient.Builder injected from Spring Boot added it, because it is instrumented.
  • Three spans were recorded, all in the same trace: the server span http get /checkout, its child the client span http get for the outgoing call, and the inventory server span, whose parent is that client span.
  • Sampling was set to 1.0. The default is 0.1, so only one request in ten would have been traced.

The trace only continues if the outgoing call uses an instrumented client. A RestClient built with RestClient.create(), as main does for the first request, is not instrumented, which is why the checkout span has no parent. Use the auto-configured RestClient.Builder or WebClient.Builder for calls between services. To send spans to a collector such as Jaeger, Tempo or an OpenTelemetry Collector, set management.opentelemetry.tracing.export.otlp.endpoint. Spring Boot 4 removed the older management.otlp.tracing.endpoint; its metadata marks the old key as an error with the new one as replacement. Exporting to a real collector is not run on this page.

@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 @Observed on a pricing method and sends a W3C baggage header with the request:

Java
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);
            }
        }
    }
}
Output
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}
  • @Observed(name = "pricing.quote") produced a timer named pricing.quote with tags for the class, the method, error=none and the extra key-value currency=EUR.
  • The same observation produced a span named after contextualName, quote price, with the same attributes, as a child of the HTTP server span http get /price.
  • The incoming baggage: tenant=acme header was read because tenant is listed in management.tracing.baggage.remote-fields, and copied into the MDC by correlation.fields, so the service's log line shows tenant=acme. An instrumented client would forward the same header to the next service.

@Observed needs two things that are easy to miss: management.observations.annotations.enabled=true, which is false by default, and spring-boot-starter-aspectj, which provides the aspect. As with every proxy-based annotation, calls on this are not observed. Keep baggage small and free of secrets: it is sent in a header on every outgoing call, including to third parties.

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 io.micrometer:micrometer-registry-prometheus, expose the endpoint with management.endpoints.web.exposure.include=health,prometheus, and point Prometheus at /actuator/prometheus. Meter names are converted to Prometheus style, so orders.completed becomes orders_completed_total.
  • Push with OTLP: spring-boot-starter-opentelemetry brings the OTLP registry. Set management.otlp.metrics.export.url to the collector's metrics endpoint; metrics are pushed every management.otlp.metrics.export.step, 1 minute by default.

What Prometheus reads is plain text. PrometheusMeterRegistry, from micrometer-registry-prometheus 1.17.2, produces it with scrape(). This program registers the meter types from the custom metrics section and prints the result:

Java
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());
    }
}
Output
# 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: orders.completed is orders_completed_total, one line per tag combination, with the description as its # HELP text. Meters without a description get an empty HELP.
  • The timer is reported in seconds, the Prometheus base unit, as payment_latency_seconds: _count 3 and _sum 1.28, the total of 0.08, 0.3 and 0.9 seconds. Its maximum became a separate gauge, 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 (le="+Inf"). Prometheus computes percentiles from buckets with histogram_quantile, across all instances, which client-side percentiles such as publishPercentiles cannot do.
  • 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 bean; the endpoint still has to be exposed. This application exposes it, sets one observation key-value, calls its own checkout endpoint three times, and reads /actuator/prometheus in both formats:

Java
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));
        }
    }
}
Output
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, text/plain;version=0.0.4. Asking for application/openmetrics-text returned OpenMetrics 1.0.0, which names the counter family orders_completed without the suffix and ends with # EOF.
  • The three requests appear as http_server_requests_seconds_count 3 for uri="/checkout", recorded by Spring MVC's observation, and the custom counter as 3.0.
  • region="eu-west-1", from management.observations.key-values.region, was added to the HTTP metric, but not to orders_completed_total: the property applies to observations only, and the counter was registered directly on the MeterRegistry. For a tag on every meter, use a MeterFilter.commonTags bean.
  • The class is not named PrometheusEndpoint: with that name, its bean prometheusEndpoint clashed with the actuator endpoint bean of the same name, and the application failed to start with a BeanDefinitionOverrideException.

The push model needs a collector, so these OTLP properties were not run:

Properties
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-1 as a low-cardinality key to every observation, a simple way to tell instances or regions apart in dashboards. The programs on this page turned OTLP export off with management.tracing.export.otlp.enabled=false and management.otlp.metrics.export.enabled=false, only because no collector was running. The Actuator page shows the built-in metrics endpoint for looking at single meters by hand.

Choosing what to instrument and how

Observability needs and the tool that fits
NeedUse
HTTP, database and messaging timingsNothing: the built-in instrumentation with the actuator starter
A business operation as a timer and a span@Observed, or Observation.createNotStarted(...).observe(...)
A business count or a current valueCounter or Gauge
Values that are not times, such as sizesDistributionSummary
Following one slow request across servicesspring-boot-starter-opentelemetry and instrumented clients
Finding the logs of one requestThe trace id in the log pattern, which Spring Boot adds by default
Context such as a tenant on every hopBaggage with remote-fields and correlation.fields
Ids, user names or other unbounded valuesHigh-cardinality key-values or span attributes, never metric tags
Percentiles across instancespublishPercentileHistogram(), computed in the monitoring system

Start with the instrumentation Spring Boot already provides, add the trace id to the logs, and add @Observed to the few operations the business cares about. The logging page explains the MDC that carries the trace id, and the @Async page shows how context is copied to other threads.