跳到主要内容
本页尚未翻译

下面显示的是英文原文。

Export

Otel sends the service's spans and metrics to an OpenTelemetry collector over OTLP, the dispatch metrics included.

Otel::builder starts an OtelBuilder. It takes the service.name, the OTLP endpoint, the messaging.system the dispatch metrics carry, and extra resource attributes such as the environment. An endpoint left unset comes from the standard OTEL_EXPORTER_OTLP_* environment, http://localhost:4317 by default. build makes the Otel without any I/O, so the app takes its layers while it is built. start consumes the Otel, builds the exporters and installs the tracer and meter providers as the process's globals. It returns a RunningOtel, the running export, which the app keeps in its state. The OTLP exporter needs the running Tokio runtime, so the app calls start from its on_startup hook, before the brokers connect. start also installs a tracing subscriber that bridges spans into the tracer, so the spans of Propagation are exported with no further wiring. With the logging feature, the bridge joins the console logger the generated main installs, in either order, and the log filter applies to the spans it exports. A service with a subscriber of its own turns the bridge off with tracing_bridge(false) and adds it to its own stack. consume_layer and publish_layer record the dispatch metrics once start has run, named by the messaging semantic conventions and labelled per subscription or destination:

InstrumentWhat it measures
messaging.client.consumed.messagesdeliveries received
messaging.process.durationhandler time
ruststream.messages.processedsettlements, by outcome: ack, nack_requeue, nack_drop, retry_after
ruststream.messages.in_flightdeliveries inside handlers
ruststream.message.queue_timetime from publish to handler, from the publish-time header the publish layer stamps
ruststream.messages.decode_failures, ruststream.messages.panicspayloads the codec rejected, handlers that panicked
messaging.client.sent.messages, messaging.client.operation.durationpublishes and their time
ruststream.message.payload.sizepublished payload sizes
ruststream.batch.sizedecoded batch sizes, recorded by batch dispatch once start has run

The duration histograms use the buckets the conventions advise, 5 ms to 10 s; view changes them per instrument. With the poll-diagnostics feature, observe_poll_diagnostics adds the poll-time gauges and counter of Diagnostics: ruststream.handler.poll.average, ruststream.handler.poll.p99 and ruststream.handler.poll.samples. observe_health adds the ruststream.app.state gauge over the health probe of a running app. The service's own instruments come from opentelemetry::global::meter and go out through the same pipeline. The example builds them in the same on_startup hook, right after start, and shares them as state; an instrument built before start records nothing. Spans and metric points are batched in the background. The after_shutdown hook reads the RunningOtel from the state and calls its shutdown, which flushes them once the brokers have stopped. Dropping a RunningOtel without shutdown does not wait for a flush, so the points still buffered when the process exits are lost. init builds and starts at once, for a hand-written #[tokio::main] that is already inside the runtime; the RunningOtel it returns hands out the layers. attach takes providers built by the caller, and start then installs no globals: an exporter of your own, or an in-memory one in a test. A Grafana dashboard over these instruments is in ruststream-grafana.

Example​

The example exports to a collector on localhost:4317; without one, the exporter retries in the background and the service keeps working:

cargo run --example otel_export --features testing,macros,memory,json,otel -- run

The app configures the export and hands it to the service.

// The integration is configured here and started inside the runtime, by the app's hooks.
#[ruststream::app]
fn app() -> impl App {
let otel = Otel::builder()
.service_name("orders")
.otlp_endpoint("http://localhost:4317")
.messaging_system("memory")
.attribute("deployment.environment", "dev")
.build();
service(otel)
}

The service takes both layers, starts the export and builds its own instrument at startup, keeps the running export in its state, and flushes it after shutdown.

fn service(otel: Otel) -> impl App {
RustStream::new(AppInfo::new("orders", "0.1.0"))
// Per delivery: consumed, processing time, outcomes, in flight, queue time.
.layer(otel.consume_layer())
// Per publish: sent, operation time, payload size, the publish-time stamp.
.publish_layer(otel.publish_layer())
// Inside the runtime, before the brokers connect: the exporters start, then the
// service's own instruments are built on the meter they installed.
.on_startup(async move |()| {
let telemetry = otel.start()?;
Ok::<_, OtelInitError>(AppState {
telemetry,
metrics: OrderMetrics {
accepted: global::meter("orders")
.u64_counter("orders_accepted")
.build(),
},
})
})
// Ships the last spans and metric points once the brokers have shut down.
.after_shutdown(async move |state| state.telemetry.shutdown().await)
.with_broker(MemoryBroker::new(), |b| b.include(accept))
}

The handler records the instrument it reads from the state.

/// The service's own instruments, built once at startup against the global meter, so they
/// export through the same pipeline as the dispatch metrics.
#[derive(Clone)]
struct OrderMetrics {
accepted: Counter<u64>,
}

#[derive(FromRef)]
struct AppState {
/// The running export, flushed by the shutdown hook; no handler reads it.
#[from_ref(skip)]
telemetry: RunningOtel,
metrics: OrderMetrics,
}

#[subscriber("orders")]
async fn accept(_order: &Order, State(metrics): State<OrderMetrics>) -> HandlerOutcome {
metrics.accepted.add(1, &[KeyValue::new("region", "eu")]);
HandlerOutcome::ack()
}