Skip to main content

Crate init_tracing_opentelemetry

Crate init_tracing_opentelemetry 

Source
Expand description

§init-tracing-opentelemetry

crates license crate version

A set of helpers to initialize (and more) tracing + opentelemetry (compose your own or use opinionated preset)

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Simple preset
    let _guard = init_tracing_opentelemetry::TracingConfig::production().init_subscriber()?;

    //...

    Ok(())
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // custom configuration
    let _guard = init_tracing_opentelemetry::TracingConfig::default()
        .with_json_format()
        .with_stderr()
        .with_log_directives("debug")
        .init_subscriber()?;

    //...

    Ok(())
}

The init_subscriber() function returns an OtelGuard instance. Following the guard pattern, this struct provides no functions but, when dropped, ensures that any pending traces/metrics are sent before it exits. The syntax let _guard is suggested to ensure that Rust does not drop the struct until the application exits.

§Re-exported crates

To avoid version mismatches (which break the OpenTelemetry global state), this crate re-exports its pinned versions of the core OpenTelemetry crates. You do not need to add them as direct dependencies in your Cargo.toml.

Instead of:

[dependencies]
init-tracing-opentelemetry = { version = "...", features = ["otlp"] }
opentelemetry = "0.33"
opentelemetry_sdk = "0.33"
tracing-opentelemetry = "0.34"

Use only:

[dependencies]
init-tracing-opentelemetry = { version = "...", features = ["otlp"] }

And reference the re-exported crates via init_tracing_opentelemetry:::

use init_tracing_opentelemetry::opentelemetry;
use init_tracing_opentelemetry::opentelemetry_sdk;
use init_tracing_opentelemetry::tracing_opentelemetry;

Re-exported crates:

Re-exportOriginal crate
init_tracing_opentelemetry::opentelemetryopentelemetry
init_tracing_opentelemetry::opentelemetry_sdkopentelemetry_sdk
init_tracing_opentelemetry::tracing_opentelemetrytracing-opentelemetry
init_tracing_opentelemetry::prometheus (with metrics-prometheus feature)prometheus

§Configuration Options

§Presets

  • TracingConfig::development() - Pretty format, stderr, with debug info
  • TracingConfig::production() - JSON format, stdout, minimal metadata
  • TracingConfig::debug() - Full verbosity with all span events
  • TracingConfig::minimal() - Compact format, no OpenTelemetry
  • TracingConfig::testing() - Minimal output for tests

§Custom Configuration

use init_tracing_opentelemetry::TracingConfig;

TracingConfig::default()
    .with_pretty_format()           // or .with_json_format(), .with_compact_format()
    .with_stderr()                  // or .with_stdout(), .with_file(path)
    .with_log_directives("debug")   // Custom log levels
    .with_line_numbers(true)        // Include line numbers
    .with_thread_names(true)        // Include thread names
    .with_otel(true)                // Enable OpenTelemetry
    .init_subscriber()
    .expect("valid tracing configuration");

§Add custom layer, modify subscriber

Use init_subscriber_ext(|subscriber| {...} ) to transform the subscriber (registry), before application of the configuration.

use init_tracing_opentelemetry::TracingConfig;
use tokio_blocked::TokioBlockedLayer;
use tracing::info;
use tracing_subscriber::layer::SubscriberExt;

#[tokio::main]
async fn main() {
    let blocked = TokioBlockedLayer::new()
        .with_warn_busy_single_poll(Some(std::time::Duration::from_micros(150)));

    let _guard = TracingConfig::default()
        .with_log_directives("info,tokio::task=trace,tokio::task::waker=warn")
        .with_span_events(tracing_subscriber::fmt::format::FmtSpan::NONE)
        .init_subscriber_ext(|subscriber| subscriber.with(blocked))
        .unwrap();

    tokio::task::spawn(async {
        // BAD!
        // This produces a warning log message.
        info!("blocking!");
        std::thread::sleep(std::time::Duration::from_secs(1));
    })
    .await
    .unwrap();

    tokio::time::sleep(tokio::time::Duration::from_secs(5)).await;
}

§Legacy API (removed)

The old procedural API (init_subscribers, build_tracer_layer, register_otel_layers_with_resource, etc. in tracing_subscriber_ext) has been removed since 0.40.0. Use TracingConfig instead.

To retrieve the current trace_id (eg to add it into error message (as header or attributes))


  let trace_id = tracing_opentelemetry_instrumentation_sdk::find_current_trace_id();
  //json!({ "error" :  "xxxxxx", "trace_id": trace_id})

§Configuration based on the environment variables

To ease setup and compliance with OpenTelemetry SDK configuration, the configuration can be done with the following environment variables (see sample init_tracing() above):

  • OTEL_EXPORTER_OTLP_TRACES_ENDPOINT fallback to OTEL_EXPORTER_OTLP_ENDPOINT for the url of the exporter / collector
  • OTEL_EXPORTER_OTLP_TRACES_PROTOCOL fallback to OTEL_EXPORTER_OTLP_PROTOCOL, fallback to auto-detection based on ENDPOINT port
  • OTEL_SDK_DISABLED=true to disable OpenTelemetry (no span created, like TracingConfig::with_otel(false)), incoming trace context is still propagated to downstream services (unless OTEL_PROPAGATORS=none)
  • OTEL_TRACES_EXPORTER=none to not export spans (no OTLP exporter created), while still creating trace context (trace_id,…) and propagating it to downstream services
  • OTEL_SERVICE_NAME for the name of the service
  • OTEL_PROPAGATORS for the configuration of the propagators
  • OTEL_TRACES_SAMPLER & OTEL_TRACES_SAMPLER_ARG for configuration of the sampler

How to enable/disable span creation, export and propagation (with axum-tracing-opentelemetry / tonic-tracing-opentelemetry middlewares):

SetupSpans / trace_id createdExportedContext propagated to downstream
default, with OTEL_EXPORTER_OTLP_*yesyesyes
OTEL_TRACES_EXPORTER=noneyesnoyes (new trace_id if none incoming)
OTEL_SDK_DISABLED=true or TracingConfig::with_otel(false)nonoonly incoming traceparent
+ OTEL_PROPAGATORS=none--no

Few other environment variables can also be used to configure OTLP exporter (eg to configure headers, authentication,, etc…):

# For GRPC:
export OTEL_EXPORTER_OTLP_TRACES_ENDPOINT="http://localhost:4317"
export OTEL_EXPORTER_OTLP_TRACES_PROTOCOL="grpc"
export OTEL_TRACES_SAMPLER="always_on"

# For HTTP:
export OTEL_EXPORTER_OTLP_TRACES_ENDPOINT="http://127.0.0.1:4318/v1/traces"
export OTEL_EXPORTER_OTLP_TRACES_PROTOCOL="http/protobuf"
export OTEL_TRACES_SAMPLER="always_on"

[!NOTE] For gRPC, an endpoint without a scheme (eg collector:4317) defaults to https:// (since opentelemetry-otlp 0.33), which requires the tls feature. For plain-text gRPC, prefix the endpoint with http:// or set OTEL_EXPORTER_OTLP_INSECURE=true (or per signal: OTEL_EXPORTER_OTLP_TRACES_INSECURE, OTEL_EXPORTER_OTLP_METRICS_INSECURE, OTEL_EXPORTER_OTLP_LOGS_INSECURE).

In the context of kubernetes, some of the above environment variables can be injected by the Opentelemetry operator (via inject-sdk):

apiVersion: apps/v1
kind: Deployment
spec:
  template:
    metadata:
      annotations:
        # to inject environment variables only by opentelemetry-operator
        instrumentation.opentelemetry.io/inject-sdk: "opentelemetry-operator/instrumentation"
        instrumentation.opentelemetry.io/container-names: "app"
      containers:
        - name: app

Or if you don’t setup inject-sdk, you can manually set the environment variable eg

apiVersion: apps/v1
kind: Deployment
spec:
  template:
    metadata:
      containers:
        - name: app
          env:
            - name: OTEL_SERVICE_NAME
              value: "app"
            - name: OTEL_EXPORTER_OTLP_PROTOCOL
              value: "grpc"
            # for otel collector in `deployment` mode, use the name of the service
            # - name: OTEL_EXPORTER_OTLP_ENDPOINT
            #   value: "http://opentelemetry-collector.opentelemetry-collector:4317"
            # for otel collector in sidecar mode (imply to deploy a sidecar CR per namespace)
            - name: OTEL_EXPORTER_OTLP_ENDPOINT
              value: "http://localhost:4317"
            # for `daemonset` mode: need to use the local daemonset (value interpolated by k8s: `$(...)`)
            # - name: OTEL_EXPORTER_OTLP_ENDPOINT
            #   value: "http://$(HOST_IP):4317"
            # - name: HOST_IP
            #   valueFrom:
            #     fieldRef:
            #       fieldPath: status.hostIP

§Troubleshot why no trace?

  • check you only have a single version of opentelemetry (could be part of your CI/build), use cargo-deny or cargo tree

    # Check only one version of opentelemetry should be used
    # else issue with setup of global (static variable)
    cargo tree -i opentelemetry

    The recommended fix is to drop direct dependencies on opentelemetry, opentelemetry_sdk, and tracing-opentelemetry and use the re-exports provided by this crate instead. This guarantees version alignment.

  • check the code of your exporter and the integration with tracing (as subscriber’s layer)

  • check the environment variables of opentelemetry OTEL_EXPORTER... and OTEL_TRACES_SAMPLER (values are logged on target otel::setup )

  • check that log target otel::tracing enable log level trace (or info if you use tracing_level_info feature) to generate span to send to opentelemetry collector.

§Metrics

To configure opentelemetry metrics, enable the metrics feature. This initializes a SdkMeterProvider and sets it globally, so instruments created anywhere via opentelemetry::metrics are wired to your configured exporter — with no dependency on tracing.

This is the primary, recommended way to produce metrics — an OpenTelemetry/Prometheus-flavored API, not a tracing one. Create the instrument once, then call it directly; dimensions are passed as KeyValue attributes at the call site, no log line is emitted, and metric cardinality stays independent of your log volume:

use init_tracing_opentelemetry::opentelemetry::{KeyValue, global};

let http_requests = global::meter("my-service").u64_counter("http_requests").build();

http_requests.add(1, &[KeyValue::new("method", "GET"), KeyValue::new("path", "/")]);

§Optional: tracing-macro bridge

Enabling the metrics feature also adds a MetricsLayer, letting specially-named fields on tracing events produce metrics, e.g. tracing::info!(monotonic_counter.index_calls = 1, method = %method). Use this only when you already emit that tracing event for other reasons (logging/spans) and want to piggyback a metric on it for free — it is not recommended as your primary metrics API, since it couples metric emission (and its cardinality) to log volume: one increment means one log line.

Configure the following set of environment variables to configure the metrics exporter (on top of those configured above):

  • OTEL_EXPORTER_OTLP_METRICS_ENDPOINT override to OTEL_EXPORTER_OTLP_ENDPOINT for the url of the exporter / collector
  • OTEL_EXPORTER_OTLP_METRICS_PROTOCOL override to OTEL_EXPORTER_OTLP_PROTOCOL, fallback to auto-detection based on ENDPOINT port
  • OTEL_EXPORTER_OTLP_METRICS_TIMEOUT to set the timeout for the connection to the exporter
  • OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE to set the temporality preference for the exporter
  • OTEL_METRIC_EXPORT_INTERVAL to set frequence of metrics export in milliseconds, defaults to 60s

§Prometheus

To expose metrics for pull-based Prometheus scraping instead of pushing via OTLP, enable the metrics-prometheus feature and call .with_metrics_prometheus() on TracingConfig:

let guard = init_tracing_opentelemetry::TracingConfig::production()
    .with_metrics_prometheus()
    .init_subscriber()?;
let registry = guard.prometheus_registry().expect("prometheus enabled").clone();

The returned prometheus::Registry (re-exported as init_tracing_opentelemetry::prometheus::Registry — no need to add prometheus as a direct dependency) can be served over HTTP with axum_tracing_opentelemetry::prometheus_metrics::router, see the axum-prometheus example.

§Logs

To configure OpenTelemetry log export, enable the logs feature. This initializes a SdkLoggerProvider and adds a log bridge layer so that tracing events are forwarded to the OpenTelemetry log pipeline and exported via OTLP.

[dependencies]
init-tracing-opentelemetry = { version = "*", features = ["otlp", "logs"] }

Standard tracing macros emit logs that are automatically bridged:

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let _guard = init_tracing_opentelemetry::TracingConfig::production().init_subscriber()?;

    tracing::error!("This is ground control to Major Tom");
    tracing::warn!("Houston, we have a problem");
    tracing::info!("We have contact");
    tracing::debug!("Roger, copy that");

    Ok(())
}

Log export can be toggled at runtime via .with_logs(bool):

use init_tracing_opentelemetry::TracingConfig;
//...
TracingConfig::default()
    .with_logs(false)   // disable log export (default: enabled when feature is active)
    .init_subscriber()
    .expect("valid tracing configuration");

Traces are automatically attached to logs as well, so if the logs are queried in Grafana (for example), the trace automatically links to the log line.

§trace_id / span_id in logs

  • OpenTelemetry logs (feature logs): every event emitted inside a span carries the trace context (trace_id, span_id). Nothing to configure.
  • fmt output (stdout, stderr, file): enable .with_fmt_trace_context(...) (FmtTraceContext::TraceId is enabled by the production() preset). Events emitted inside a span get the current trace context (field names and hex encoding as recommended by OpenTelemetry for non-OTLP log formats):
    • FmtTraceContext::TraceId: trace_id only, enough to link logs to traces (e.g. Grafana Loki -> Tempo)
    • FmtTraceContext::TraceIdSpanId: trace_id and span_id (e.g. required by Datadog log/trace correlation)
    • JSON: {"trace_id":"d097ae91be74af8dee5c1c8b97b60215","span_id":"5ffc1a8e3b0d2c47","timestamp":...,"level":"INFO",...}
    • pretty / full / compact / logfmt: trace_id=d097ae91be74af8dee5c1c8b97b60215 span_id=5ffc1a8e3b0d2c47 <usual line> (e.g. logfmt: trace_id=d097... span_id=5ffc... ts=... level=info ... message=...)
use init_tracing_opentelemetry::{FmtTraceContext, TracingConfig};
//...
TracingConfig::default()
    .with_json_format()
    .with_fmt_trace_context(FmtTraceContext::TraceId)
    .init_subscriber()
    .expect("valid tracing configuration");

screenshot of grafana logs

Configure the following environment variables to control the logs exporter (in addition to the shared variables above):

  • OTEL_EXPORTER_OTLP_LOGS_ENDPOINT overrides OTEL_EXPORTER_OTLP_ENDPOINT for the log pipeline; for HTTP the path /v1/logs is appended automatically
  • OTEL_EXPORTER_OTLP_LOGS_PROTOCOL overrides OTEL_EXPORTER_OTLP_PROTOCOL, falls back to port-based auto-detection
# For GRPC:
export OTEL_EXPORTER_OTLP_LOGS_ENDPOINT="http://localhost:4317"
export OTEL_EXPORTER_OTLP_LOGS_PROTOCOL="grpc"

# For HTTP:
export OTEL_EXPORTER_OTLP_LOGS_ENDPOINT="http://127.0.0.1:4318/v1/logs"
export OTEL_EXPORTER_OTLP_LOGS_PROTOCOL="http/protobuf"

Note: A protocol must be set (via env var or inferable from the endpoint port). If neither is found, no log exporter is created and a warning is emitted on target otel::setup.

§Changelog - History

CHANGELOG.md

Re-exports§

pub use config::FeatureSet;tracing_subscriber_ext
pub use config::FmtTraceContext;tracing_subscriber_ext
pub use config::Guard;tracing_subscriber_ext
pub use config::LevelConfig;tracing_subscriber_ext
pub use config::LogFormat;tracing_subscriber_ext
pub use config::LogTimer;tracing_subscriber_ext
pub use config::OtelConfig;tracing_subscriber_ext
pub use config::TracingConfig;tracing_subscriber_ext
pub use config::WriterConfig;tracing_subscriber_ext
pub use formats::CompactLayerBuilder;tracing_subscriber_ext
pub use formats::FullLayerBuilder;tracing_subscriber_ext
pub use formats::JsonLayerBuilder;tracing_subscriber_ext
pub use formats::LayerBuilder;tracing_subscriber_ext
pub use formats::PrettyLayerBuilder;tracing_subscriber_ext
pub use formats::LogfmtLayerBuilder;logfmt and tracing_subscriber_ext
pub use opentelemetry;
pub use opentelemetry_sdk;
pub use prometheus;metrics-prometheus
pub use tracing_opentelemetry;

Modules§

configtracing_subscriber_ext
Flexible tracing configuration with builder pattern.
formatstracing_subscriber_ext
Format-specific layer builders for tracing output.
otlpotlp
resourcetracer
stdiostdout

Enums§

Error
Errors returned when initializing or configuring tracing.

Functions§

init_propagator
Configure the global propagator based on content of the env variable OTEL_PROPAGATORS Specifies Propagators to be used in a comma-separated list. Default value: "tracecontext,baggage" Example: export OTEL_PROPAGATORS="b3" Accepted values for OTEL_PROPAGATORS are: