Skip to content

metrics: Implement pushing via OLTP - #7664

Merged
francislavoie merged 2 commits into
caddyserver:masterfrom
dunglas:feat/metrics-otlp
Apr 25, 2026
Merged

francislavoie merged 2 commits into
caddyserver:masterfrom
dunglas:feat/metrics-otlp

Conversation

@dunglas

@dunglas dunglas commented Apr 22, 2026 •

Copy link
Copy Markdown
Collaborator

Adds an otlp sub-directive to the existing metrics global directive.

When enabled, pushes Caddy's metrics via OTLP. It's useful for deploying Caddy with an OTLP-native observability stack (Grafana Alloy, OpenTelemetry Collector, Tempo/Mimir, Honeycomb, …) as it doesn't require an additional Prometheus scrape job.

The exporter, protocol, endpoint, headers, resource attributes, and collection interval are all driven by the standard OTEL_* environment variables — mirroring the ergonomics of the existing tracing directive.
No new Caddyfile options beyond the single flag are introduced; users who need non-default protocols/endpoints/etc. set the relevant OTEL_* env var.

Closes (a part of) dunglas/mercure#1194. and

Usage

{
    metrics {
        otlp
    }
}

:2080 {
    respond "Hello"
}
OTEL_EXPORTER_OTLP_ENDPOINT=http://collector:4318 \
    OTEL_METRICS_EXPORTER=otlp \
    ./caddy run

All metrics registered with ctx.GetMetricsRegistry() (i.e. everything exposed at /metrics today — caddy_http_*, caddy_reverse_proxy_*, plus collectors from third-party modules) now land at the OTLP endpoint too, with web_engine.name / web_engine.version resource attributes set from ServerHeader and caddy.Version().

Internally it:

  1. Registers the Prometheus → OpenTelemetry bridge over ctx.GetMetricsRegistry() as the fallback MetricProducer — so the existing registry is the default source when OTEL_METRICS_PRODUCERS is unset; users can still override.
  2. Calls autoexport.NewMetricReader for the reader/exporter. This honours OTEL_METRICS_EXPORTER (defaulting to otlp), OTEL_EXPORTER_OTLP_PROTOCOL (http/protobuf or grpc), endpoint/headers/interval env vars, and short-circuits to a no-op reader when OTEL_METRICS_EXPORTER=none.
  3. Builds a MeterProvider with a resource tagged web_engine.name=<ServerHeader> + web_engine.version=<caddy.Version()>.

Assistance Disclosure

I used Claude Code.

Adds an `otlp` sub-directive to the global `metrics { … }` Caddyfile
block (and the matching field on the `caddyhttp.Metrics` struct) that,
when enabled, wires an OpenTelemetry `MeterProvider` + `PeriodicReader`
around the process-wide Prometheus registry. Every metric already
registered with `ctx.GetMetricsRegistry()` is then pushed via OTLP in
parallel with the existing scrape endpoints.

The exporter, protocol, endpoint, headers and collection interval are
auto-configured from the standard OTEL_* environment variables via
`go.opentelemetry.io/contrib/exporters/autoexport.NewMetricReader`,
matching the ergonomics of the existing `tracing` directive. Setting
`OTEL_METRICS_EXPORTER=none` short-circuits to a no-op reader. The
Prometheus -> OTel bridge from `go.opentelemetry.io/contrib/bridges/
prometheus` is registered as the fallback `MetricProducer` so the
existing registry is the default source when `OTEL_METRICS_PRODUCERS`
is unset.

Provider lifecycle:

  - provisionOTLP is called from `App.Provision` right after the
    existing `scanConfigForHosts` pass, so it benefits from the same
    one-time initialisation and config-reload flow.
  - `App.Stop` calls the new `shutdown` helper, which `ForceFlush`es
    and `Shutdown`s the provider so the collector receives a final
    batch before the process exits.

Usage:

    {
        metrics {
            otlp
        }
    }

    OTEL_EXPORTER_OTLP_ENDPOINT=http://collector:4318 \
      OTEL_METRICS_EXPORTER=otlp ./caddy run

Covers the metrics half of the discussion in the Mercure issue at
dunglas/mercure#1194, but is useful for any Caddy user in an OTLP-
native observability stack.
Copilot AI review requested due to automatic review settings April 22, 2026 10:18

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Adds optional OTLP export for Caddy HTTP app metrics via a new metrics { otlp } global subdirective, aligning configuration with existing OpenTelemetry ergonomics (driven by OTEL_* env vars).

Changes:

  • Add otlp flag to HTTP app metrics config, provisioning an OTLP-backed OTel MeterProvider and shutting it down on app stop.
  • Bridge the existing Prometheus registry into OTel metrics export (Prometheus → OTel bridge) and tag exported metrics with web_engine.* resource attributes.
  • Add Caddyfile-adapt integration test to validate the new metrics { otlp } directive output.

Reviewed changes

Copilot reviewed 6 out of 6 changed files in this pull request and generated 2 comments.

Show a summary per file
File Description
modules/caddyhttp/metrics.go Introduces OTLP provisioning/shutdown and adds otlp config field; switches sanitizers import alias.
modules/caddyhttp/app.go Hooks OTLP metrics provisioning into Provision and shutdown into Stop.
caddyconfig/httpcaddyfile/options.go Adds otlp token support under global metrics options.
caddytest/integration/caddyfile_adapt/metrics_otlp.caddyfiletest Adds adapter test verifying metrics.otlp: true JSON output.
modules/caddyhttp/tracing/tracer.go Aligns tracing resource web_engine.name with caddyhttp.ServerHeader.
go.mod Adds direct dependencies for OTel Prometheus bridge and SDK metric module.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread modules/caddyhttp/metrics.go Resolved
Comment thread modules/caddyhttp/metrics.go Resolved
Two follow-ups on the caddyhttp/metrics.go OTLP work:

- The `autoexport.WithFallbackMetricProducer` call is a package-level
  setter (it returns nothing), not a MetricOption. The previous comment
  glossed over that, which reads as a bug when you land on the call
  fresh (the `With*` naming strongly suggests an option constructor).
  Rewrite the comment to call this out explicitly so nobody tries to
  pass the result into `NewMetricReader` (which would not compile
  anyway, but nothing in the code itself tells you that).

- Add three small tests in modules/caddyhttp/metrics_test.go:
  - provisionOTLP is a no-op when OTLP is disabled and doesn't create
    a MeterProvider.
  - With OTEL_METRICS_EXPORTER=none (autoexport's built-in noop
    reader — no network), provisionOTLP sets up a MeterProvider and
    shutdown tears it down cleanly.
  - shutdown on a nil *Metrics is a no-op, which is what lets
    App.Stop call it without guarding on app.Metrics being set.
@francislavoie francislavoie added the feature ⚙️ New feature or request label Apr 25, 2026
@francislavoie francislavoie changed the title feat: push metrics via OTLP metrics: Implement pushing via OLTP Apr 25, 2026

@francislavoie francislavoie left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Unfortunately I'm not too sure who's equipped to review this. Most of the core team doesn't play around with metrics too much. But it looks sensible to me.

@francislavoie francislavoie added this to the v2.11.3 milestone Apr 25, 2026
@francislavoie
francislavoie merged commit 2a3ed96 into caddyserver:master Apr 25, 2026
28 checks passed
social4hyq pushed a commit to social4hyq/homebrew-core that referenced this pull request Sep 20, 2026
caddy 2.11.3

Created-by: HarmonybrewBot
Commit-by: HarmonybrewBot
Merged-by: HarmonybrewBot
Description: Created by `brew bump`

---

Created with `brew bump-formula-pr`.

- [ ] `resource` blocks have been checked for updates.
<details>
  <summary>release notes</summary>
  <pre>This release improves several aspects of Caddy with minor features, bug fixes, and security patches. Thank you to everyone and their bots who contributed to help make this release the best one yet!

**Security patches:**

- fastcgi: Carrying over a patch from FrankenPHP for a bug that could allow non-PHP files to be executed; collaborated on by @dunglas, @KC1zs4, and @chenjj.
- vars: A more thorough fix for GHSA-m2w3-8f23-hxxf, collaborated by @everping and @vnxme.
- admin: Array index normalization to prevent remote admin socket auth bypass, by @Amemoyoi and bot.
- admin: More rigorous path prefix matching to prevent remote admin socket auth bypass, by @Amemoyoi and bot.

We've also merged a couple PRs that fix upstream security bugs in other projects like quic-go and CertMagic. Thank you to @marten-seemann for maintaining quic-go so diligently!

## What's Changed
* caddyhttp: Sync placeholder expansion in `vars` and `vars_regexp` by @vnxme in caddyserver/caddy#7573
* caddytls: Avoid ACME fallback for implicit Tailscale *.ts.net policies by @steadytao in caddyserver/caddy#7577
* chore: Resolve recent CI failures by @mholt in caddyserver/caddy#7593
* caddytls: Consolidate empty APs more smartly by @mholt in caddyserver/caddy#7567
* rewrite: skip query rename when source key is absent by @steadytao in caddyserver/caddy#7599
* root: introduce down-propagating Helper.BlockState for other directives/plugins to use by @henderkes in caddyserver/caddy#7594
* http: make zstd checksum configurable by @ottenhoff in caddyserver/caddy#7586
* notify: Always send "READY=1" even after an error by @francislavoie in caddyserver/caddy#7597
* reverseproxy: Fix check for `header_up Host {upstream_hostport}` redundancy by @yubiuser in caddyserver/caddy#7564
* caddytls: Expand placeholders in dns_challenge override_domain tls parameter by @pberkel in caddyserver/caddy#7609
* tls: add system and combined CA pool modules by @HarshPatel5940 in caddyserver/caddy#7406
* vars: Don't expand placeholders in values by @vnxme in caddyserver/caddy#7629
* build(deps): bump go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp from 1.42.0 to 1.43.0 by @dependabot[bot] in caddyserver/caddy#7637
* build(deps): bump the all-updates group across 1 directory with 11 updates by @dependabot[bot] in caddyserver/caddy#7641
* reverseproxy: make stream copy buffer size configurable by @steadytao in caddyserver/caddy#7627
* vars: Add matcher placeholder handling tests by @steadytao in caddyserver/caddy#7640
* build(deps): bump github.com/go-jose/go-jose/v4 from 4.1.3 to 4.1.4 by @dependabot[bot] in caddyserver/caddy#7621
* logging: Add journald encoder wrapper by @steadytao in caddyserver/caddy#7623
* caddyfile: Improve import/global options UX for imports before global options by @steadytao in caddyserver/caddy#7642
* chore: replace `interface{}` with `any` for modernization by @tsinglua in caddyserver/caddy#7571
* chore: bump timberjack to v1.4.1 by @DeRuina in caddyserver/caddy#7618
* logging: Preserve ts for journald-wrapped JSON logs by @steadytao in caddyserver/caddy#7644
* fileserver: show symlink targets verbatim (#7476) by @maxtruxa in caddyserver/caddy#7579
* fix(caddyfile): {block} in snippet by @prettysunflower in caddyserver/caddy#7558
* caddyhttp: Document missing placeholders for escaped URI and prefixed query by @steffenbusch in caddyserver/caddy#7659
* chore: add `AGENTS.md` by @mohammed90 in caddyserver/caddy#7652
* build(deps): bump github.com/jackc/pgx/v5 from 5.8.0 to 5.9.0 by @dependabot[bot] in caddyserver/caddy#7655
* admin: Redact sensitive request headers in API logs by @steadytao in caddyserver/caddy#7578
* reverseproxy: add `lb_retry_match` condition on response status by @seroperson in caddyserver/caddy#7569
* caddyhttp: prefer port 443 in auto-HTTPS and add tests by @mholt in caddyserver/caddy#7666
* fix: Propagate ECH keys to the QUIC listener by @steadytao in caddyserver/caddy#7670
* chore: Use atomics where appropriate by @francislavoie in caddyserver/caddy#7648
* metrics: Implement pushing via OLTP by @dunglas in caddyserver/caddy#7664
* logging: Add regression coverage for rotated file mode by @steadytao in caddyserver/caddy#7620
* httpcaddyfile: Inherit global ACME issuer settings in tls shortcuts by @steadytao in caddyserver/caddy#7617
* build(deps): bump github.com/jackc/pgx/v5 from 5.9.0 to 5.9.2 by @dependabot[bot] in caddyserver/caddy#7668
* admin: require path segment boundary in remote access control by @Amemoyoi in caddyserver/caddy#7673
* reverseproxy: Add ability to clear dynamic upstreams cache during retries by @mholt in caddyserver/caddy#7662
* listeners: clean up stale Unix socket files on Windows by @mfrischknecht in caddyserver/caddy#7676
* admin: reject non-canonical config array indices by @Amemoyoi in caddyserver/caddy#7592
* caddytls: Expand ACME credentials by @tribut in caddyserver/caddy#7554
* caddyauth: set user placeholders before auth rejection by @cyphercodes in caddyserver/caddy#7685
* caddyauth: revert user placeholders on auth rejection by @steadytao in caddyserver/caddy#7688
* chore: Fix golangci-lint 2.12.1 findings by @steadytao in caddyserver/caddy#7690
* httpcaddyfile: accept duration strings for log sampling interval by @tomholford in caddyserver/caddy#7694
* tls: Add alpn to managed HTTPS records by @steadytao in caddyserver/caddy#7653
* caddytls: avoid duplicate automation for wildcard-covered hosts by @Rijul-A in caddyserver/caddy#7697
* docs: add documentation for fileExists and fileStat template functions by @steffenbusch in caddyserver/caddy#7700
* rewrite: escape file matcher paths before rewriting by @cyphercodes in caddyserver/caddy#7683
* metrics: Add nil check for metricsHandler in AdminMetrics.serveHTTP by @Br1an67 in caddyserver/caddy#7553

## New Contributors
* @steadytao made their first contribution in caddyserver/caddy#7577
* @henderkes made their first contribution in caddyserver/caddy#7594
* @yubiuser made their first contribution in caddyserver/caddy#7564
* @pberkel made their first contribution in caddyserver/caddy#7609
* @HarshPatel5940 made their first contribution in caddyserver/caddy#7406
* @tsinglua made their first contribution in caddyserver/caddy#7571
* @maxtruxa made their first contribution in caddyserver/caddy#7579
* @seroperson made their first contribution in caddyserver/caddy#7569
* @Amemoyoi made their first contribution in caddyserver/caddy#7673
* @mfrischknecht made their first contribution in caddyserver/caddy#7676
* @tribut made their first contribution in caddyserver/caddy#7554
* @cyphercodes made their first contribution in caddyserver/caddy#7685
* @tomholford made their first contribution in caddyserver/caddy#7694
* @Rijul-A made their first contribution in caddyserver/caddy#7697
* @Br1an67 made their first contribution in caddyserver/caddy#7553

**Full Changelog**: https://github.com/caddyserver/caddy/compare/v2.11.2...v2.11.3</pre>
  <p>View the full release notes at <a href="https://github.com/caddyserver/caddy/releases/tag/v2.11.3">https://github.com/caddyserver/caddy/releases/tag/v2.11.3</a>.</p>
</details>
<hr>



See merge request: Harmonybrew/homebrew-core!842
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

feature ⚙️ New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants