getsentry / sentry-rust

Official Sentry SDK for Rust
https://sentry.io/
Apache License 2.0
620 stars 153 forks source link

tracing: send spans' attributes along with the event ones #629

Closed tsionyx closed 11 months ago

tsionyx commented 12 months ago

Implementing https://github.com/getsentry/sentry-rust/issues/617

Adds a enable_span_attributes() method for the sentry_tracing::SentryLayer that activates the desired behaviour. The root span's attributes can only be propagated once the traces enabled (e.g. through ClientOptions::traces_sample_rate).

tsionyx commented 11 months ago
use sentry::{
    integrations::tracing::{self as sentry_tracing, EventFilter},
    ClientOptions,
};
use tracing::{span, warn, Level};
use tracing_subscriber::{layer::SubscriberExt as _, util::SubscriberInitExt as _};

const DSN: &str = "MY_DSN";

fn main() {
    let _guard = sentry::init((
        DSN,
        ClientOptions {
            traces_sample_rate: 1.0,
            ..Default::default()
        },
    ));

    let sentry_layer = sentry_tracing::layer()
        .enable_span_attributes()
        .event_filter(|md| match *md.level() {
            Level::ERROR | Level::WARN => EventFilter::Event,
            _ => EventFilter::Ignore,
        });

    tracing_subscriber::registry()
        .with(sentry_layer)
        .with(tracing_subscriber::fmt::layer())
        .init();

    // create very simple spans hierarchy
    let span = span!(Level::ERROR, "root span", span_int = 42, span_str = "hello");
    span.in_scope(|| {
        span!(
            Level::WARN,
            "child span",
            span_num = 144,
            span_str = "world"
        )
        .in_scope(|| {
            warn!(event_data = 3.1417, "The event message");
        })
    });
}

gives the following output in the dashboard

image

codecov[bot] commented 11 months ago

Codecov Report

Merging #629 (3c65139) into master (c53da38) will decrease coverage by 0.29%. The diff coverage is 39.70%.

Additional details and impacted files ```diff @@ Coverage Diff @@ ## master #629 +/- ## ========================================== - Coverage 73.03% 72.75% -0.29% ========================================== Files 59 59 Lines 6658 6706 +48 ========================================== + Hits 4863 4879 +16 - Misses 1795 1827 +32 ```