Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Quick start

Cargo.toml:

[dependencies]
gcloud-observability = { version = "0.31", features = ["otlp"] }
opentelemetry_sdk = "0.33"
tracing = "0.1"
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
tracing-opentelemetry = "0.34"
tokio = { version = "1", features = ["macros", "rt-multi-thread"] }

Minimum supported Rust version is 1.91.

The logs feature, which provides the logging layer, is on by default. otlp adds the span exporter for the Telemetry API.

The setup below exports spans through OTLP and writes every event to stdout as a Cloud Logging JSON line that carries the trace and span it happened in:

    let otlp = GcpOtlpExporterBuilder::new(google_project_id.clone()).with_resource(
        opentelemetry_sdk::Resource::builder()
            .with_service_name("quickstart-example")
            .build(),
    );
    let tracer_provider = otlp.create_provider().await?;
    let tracer = otlp.install(&tracer_provider);

    let log_layer = GcpCloudLoggingLayerBuilder::new(google_project_id).build()?;

    // The OpenTelemetry layer goes before the logging layer: the logging layer reads the span
    // context the OpenTelemetry layer attaches, and sees only what is registered ahead of it.
    let subscriber = Registry::default()
        .with(EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("info")))
        .with(tracing_opentelemetry::layer().with_tracer(tracer))
        .with(log_layer);
    tracing::subscriber::set_global_default(subscriber)?;

The setup needs these imports:

use gcloud_observability::logs::GcpCloudLoggingLayerBuilder;
use gcloud_observability::otlp::GcpOtlpExporterBuilder;
use tracing_subscriber::layer::SubscriberExt;
use tracing_subscriber::{EnvFilter, Registry};

The JSON lines are what the Cloud Logging agent of GKE, Cloud Run and GCE collects from stdout. Run on a laptop they only print; the spans reach the Telemetry API either way.

Call tracer_provider.shutdown() before the process ends. It exports the spans still queued, and blocks the calling thread, so it needs the multi-threaded Tokio runtime that #[tokio::main] starts.

The credentials are found by ADC and need the role described in Authentication.

Full example available here.

Running the examples

All examples are in the examples directory, named after their goal. Each example names its features in its header comment and in required-features in Cargo.toml:

PROJECT_ID=<your-google-project-id> cargo run --example quickstart --features logs,otlp
GoalExamples
Logginglogging-dev-and-prod, logging-cloud-logging-api, logging-otlp
Errors and panicserrors-error-reporting, errors-panic-hook
Tracestraces-otlp, traces-cloud-trace-api
Traces with correlated logstraces-and-logs-otlp, traces-and-logs-cloud-trace-api
Metricsmetrics-otlp