OpenTelemetry
Traces, logs and metrics, W3C propagation and OTLP export — wired by one line in main, configured by the specification's own OTEL_* variables.
nest-rs-opentelemetry is the OpenTelemetry layer of the framework. It installs
a tracing subscriber, batches traces / logs /
metrics through the official
opentelemetry +
opentelemetry_sdk +
opentelemetry-otlp crates,
follows the
opentelemetry-semantic-conventions
for resource and HTTP attributes, and links the tracing span tree to its OTel
counterpart through
tracing-opentelemetry.
Three signal types ship in one crate, behind one line of main:
- Traces — every request, job and scheduled tick
opens a span, and so does every unit a package declares, exported under the
same trace and span ids its log lines carry; W3C
traceparentpropagation and sampling, seeded onto the framework’s span constructor, stitch distributed traces together. - Logs —
tracing::info!and friends flow to the console and to OTel logs (viaopentelemetry-appender-tracing) with structured fields, configurable level per layer, and JSON for prod. - Metrics — inject
Arc<Metrics>and record on counters / histograms / gauges, named as the OpenTelemetry Metrics API names them; metrics batch on aPeriodicReaderand export through the same OTLP endpoint as the traces.
Install
Section titled “Install”cargo add nest-rs --features opentelemetryA headless binary (a queue worker) and an app serving HTTP install the same line: what this crate adds hangs off the framework’s span constructor, which every edge opens — see Feature flags below.
Wire it in
Section titled “Wire it in”use anyhow::Result;use nest_rs::core::App;use nest_rs::opentelemetry::OpenTelemetry;
use auth::AuthModule;
#[nest_rs::main]async fn main() -> Result<()> { let _otel = OpenTelemetry::init()?;
App::builder() .module::<AuthModule>() .build() .await? .run() .await}One line, one rule: there is no module to import for it, and nothing for a
suite to call. OpenTelemetry::init()? installs the global subscriber and
must run before App::builder(). It takes no name: the
service is the binary #[nest_rs::main] started, named and versioned from its
package’s manifest. The returned guard flushes batch exporters on Drop, so it
must live until main returns — bind it to _otel, never _, which drops it
on the spot. The guard is #[must_use], and clippy::let_underscore_must_use
refuses the discard: a nestrs new workspace denies it for every member; a
project of your own turns it on in its [workspace.lints.clippy], or the
trap stays open, since clippy leaves that lint off by default. That flush is
bounded: the three providers export at once, and what is still exporting after
three seconds (FLUSH_TIMEOUT) is abandoned with a line on stderr naming it,
so a collector that stopped answering delays the exit by three seconds and
never holds it. Three is the step of
the way down before the console’s last
second, which sums to 29.5 seconds under a Kubernetes pod’s 30-second grace.
Nothing is mounted per request: what it adds to a span reaches every edge
through the framework’s span constructor. The one module of this crate,
OpenTelemetryModule, provides Metrics to the
module whose provider injects them, and an app recording no metric of its own
imports it nowhere.
init stays a line of main rather than a #[nest_rs::main] key: a pinned
config goes through init_with, and one way to start telemetry beats two.
Configure the exporter
Section titled “Configure the exporter”The exporter reads the variables the OpenTelemetry specification names —
OTEL_*, with no prefix — over what OpenTelemetryConfig pins. Every one of
them, and the TLS an export runs over, is on
OpenTelemetry configuration.
Feature flags
Section titled “Feature flags”nest-rs-opentelemetry ships one feature of its own, which you never name: the
umbrella’s opentelemetry feature turns it on.
otlp(default) — pulls theopentelemetry-*crates, installs the OTLP exporters for traces / metrics / logs, bridgestracingevents into OTel logs, seeds the remote parent link and the sampler’s verdict onto the framework’s span constructor, and providesMetricsthroughOpenTelemetryModule. Without it, the subscriber stays a console-onlytracingsetup, and neitherMetricsnor its module exists — useful for a tiny binary that should not link the OTel SDK. Its boot line names the service as the exporters’ resource would, under the same variables and the same refusals. Such a binary still reads the three selectors:noneis all it honours, and any other value,otlpincluded, fails the boot naming the variable, since nothing would ship. For the same reason an endpoint set for a signal its selector leaves on —OTEL_EXPORTER_OTLP_ENDPOINT, a signal’s own, or a pinnedotlp_endpoint— fails the boot naming it and the feature, unlessOTEL_SDK_DISABLED=true.
There is no http feature: the remote parent link and the sampling decision
reach every edge through the span constructor, so a queue worker gets them as
an HTTP app does, and nothing here compiles the HTTP transport. Without this
crate you still get the request span, the access log and the whole W3C trace
context — trace_id, span_id, traceparent across a queue: those are the
transport’s, and they do not wait on it.
nest-rs = { workspace = true, features = ["opentelemetry"] }Boot-time safety
Section titled “Boot-time safety”Error: OTEL_EXPORTER_OTLP_ENDPOINT sets an OTLP endpoint, but nothing exports toit: the process logs through the kernel's console alone — add `let _otel =nest_rs::opentelemetry::OpenTelemetry::init()?;` at the top of `main`, with theumbrella's `opentelemetry` feature, or set OTEL_SDK_DISABLED=true where thisbinary exports nothingForgetting OpenTelemetry::init is the failure mode that hurts in production:
the backend stays quiet, the team thinks observability is on, and the first
time someone needs a trace there’s nothing to grep. So the deployment’s intent
decides: App::run refuses to start when OTEL_EXPORTER_OTLP_ENDPOINT, or a
signal’s own endpoint, is set for a signal the deployment leaves on — no
OTEL_SDK_DISABLED=true, no OTEL_TRACES_EXPORTER=none — while the process
logs through the kernel’s console alone, which exports nothing. The check
lives in the kernel, so it holds in a binary that links no telemetry at all.
An init with no endpoint exports nothing either, so a binary run on your
machine is never refused; an app that installs a subscriber of its own before
the boot is its own to judge. The refusal is App::run’s alone: a suite boots
through App::builder().build(), never run, so a .env naming a local
collector never stops one.
use api::ApiModule;use features::Role;use features::testing::{ORG_ID, claims, client};use nest_rs::http::header;use nest_rs::testing::TestApp;
#[tokio::test]async fn users_list_returns_a_page() { let app = TestApp::builder() .module::<ApiModule>() .ephemeral_database::<migrations::Migrator>() .ephemeral_signing_key() .build() .await .unwrap(); let bearer = app.bearer(&claims(ORG_ID, Role::Admin, client()));
app.http() .get("/users") .header(header::AUTHORIZATION, &bearer) .send() .await .assert_status_is_ok();}A suite boots the module main boots and never runs main, so it asks
nothing of telemetry: it logs through the console the boot installs, under
RUST_LOG and <PREFIX>_LOG_*, and exports nothing. A provider injecting
Metrics gets them all the same, recording on a meter nothing exports.
In this section
Section titled “In this section”Basics
Section titled “Basics”- Traces — the span every request, job and tick opens, W3C propagation and sampling.
- Logs — the record shape, the ids every line carries, a level per layer and JSON for prod.
All options
Section titled “All options”- The operation log — one line per unit of work, what each edge’s line names, and the HTTP access log.
- Metrics — counters, histograms and gauges a
provider records through
Arc<Metrics>. - OpenTelemetry configuration — the
OTEL_*variables, and the TLS, timeouts and headers an encrypted export runs on.
Reference
Section titled “Reference”crates/nest-rs-opentelemetry/—OpenTelemetry::init,OpenTelemetryConfig,OpenTelemetryModule, and the metrics vocabulary:Metrics,Counter,UpDownCounter,Histogram,Gauge,Attribute,AttributeValue,Describe. The console’s format,OpenTelemetryConfig::log_format, isnest_rs::core::logging::LogFormat.crates/nest-rs-server-timing/— theServer-Timingheader middleware.
Going further
Section titled “Going further”- Correlation — the trace context underneath, which waits on no crate.
- Server-Timing — the companion header summarising a request’s main spans.