pub fn init(
spin_version: String,
histogram_buckets: Vec<HistogramBuckets>,
) -> Result<()>Expand description
Initializes telemetry for Spin using the tracing library.
Under the hood this involves initializing a tracing::Subscriber with multiple Layers. One
Layer emits tracing events to stderr, and another sends spans to an OTel collector. Metrics
are handled separately from the tracing Layers: a global OTel meter provider is registered
directly, and the metric macros in metrics record to it without going through tracing.
Configuration for the OTel layers and the meter provider is pulled from the environment. This sets the global tracing::Subscriber and the global OTel meter provider, so it should be called early in the process before any other code that emits telemetry.
Examples of emitting traces from Spin:
#[instrument(name = "span_name", err(level = Level::INFO), fields(otel.name = "dynamically set name"))]
fn func_you_want_to_trace() -> anyhow::Result<String> {
Ok("Hello, world!".to_string())
}Some notes on tracing:
- If you don’t want the span to be collected by default emit it at a trace or debug level.
- Make sure you
.in_current_span()any spawned tasks so the span context is propagated. - Use the otel.name attribute to dynamically set the span name.
- Use the err argument to have instrument automatically handle errors.
Examples of emitting metrics from Spin:
spin_telemetry::metrics::counter!(spin.metric_name = 1, metric_attribute = "value");histogram_buckets lets callers override the OTel default histogram boundaries for specific
metrics (e.g. those recorded on a 0.0..=1.0 scale rather than millisecond durations). Pass an
empty Vec to use the defaults for everything.