Skip to main content

Scope

Struct Scope 

Source
pub struct Scope { /* private fields */ }
Available on crate feature client only.
Expand description

Holds contextual data for the current scope.

The scope is an object that can be cloned efficiently and stores data that is locally relevant to an event. For instance the scope will hold recorded breadcrumbs and similar information.

The scope can be interacted with in two ways:

  1. the scope is routinely updated with information by functions such as add_breadcrumb which will modify the currently top-most scope.
  2. the topmost scope can also be configured through the configure_scope method.

Note that the scope can only be modified but not inspected. Only the client can use the scope to extract information currently.

Implementations§

Source§

impl Scope

Source

pub fn clear(&mut self)

Clear the scope.

By default a scope will inherit all values from the higher scope. In some situations this might not be what a user wants. Calling this method will wipe all data contained within.

Source

pub fn clear_breadcrumbs(&mut self)

Deletes current breadcrumbs from the scope.

Source

pub fn set_level(&mut self, level: Option<Level>)

Sets a level override.

Examples found in repository?
examples/send-with-extra.rs (line 12)
3fn main() {
4    let _sentry = sentry::init(
5        sentry::ClientOptions::new()
6            .maybe_release(sentry::release_name!())
7            .debug(true),
8    );
9
10    sentry::with_scope(
11        |scope| {
12            scope.set_level(Some(sentry::Level::Warning));
13            scope.set_fingerprint(Some(["a-message"].as_ref()));
14            scope.set_tag("foo", "bar");
15        },
16        || {
17            panic!("Shit's on fire yo. 🔥 🚒");
18        },
19    );
20}
Source

pub fn set_fingerprint(&mut self, fingerprint: Option<&[&str]>)

Sets the fingerprint.

Examples found in repository?
examples/message-demo.rs (line 10)
3fn main() {
4    let _sentry = sentry::init(
5        sentry::ClientOptions::new()
6            .maybe_release(sentry::release_name!())
7            .debug(true),
8    );
9    sentry::configure_scope(|scope| {
10        scope.set_fingerprint(Some(["a-message"].as_ref()));
11        scope.set_tag("foo", "bar");
12    });
13
14    sentry::capture_message("This is recorded as a warning now", sentry::Level::Warning);
15}
More examples
Hide additional examples
examples/send-with-extra.rs (line 13)
3fn main() {
4    let _sentry = sentry::init(
5        sentry::ClientOptions::new()
6            .maybe_release(sentry::release_name!())
7            .debug(true),
8    );
9
10    sentry::with_scope(
11        |scope| {
12            scope.set_level(Some(sentry::Level::Warning));
13            scope.set_fingerprint(Some(["a-message"].as_ref()));
14            scope.set_tag("foo", "bar");
15        },
16        || {
17            panic!("Shit's on fire yo. 🔥 🚒");
18        },
19    );
20}
examples/event-processors.rs (line 22)
3fn main() {
4    let _sentry = sentry::init(
5        sentry::ClientOptions::new()
6            .maybe_release(sentry::release_name!())
7            .debug(true),
8    );
9
10    sentry::configure_scope(|scope| {
11        scope.add_event_processor(|mut event| {
12            event.request = Some(sentry::protocol::Request {
13                url: Some("https://example.com/".parse().unwrap()),
14                method: Some("GET".into()),
15                ..Default::default()
16            });
17            Some(event)
18        });
19    });
20
21    sentry::configure_scope(|scope| {
22        scope.set_fingerprint(Some(["a-message"].as_ref()));
23        scope.set_tag("foo", "bar");
24    });
25
26    let id = sentry::capture_message("An HTTP request failed.", sentry::Level::Error);
27    println!("sent event {id}");
28}
Source

pub fn set_transaction(&mut self, transaction: Option<&str>)

Sets the transaction.

Source

pub fn set_user(&mut self, user: Option<User>)

Sets the user for the current scope.

Source

pub fn user(&self) -> Option<&User>

Retrieves the user of the current scope.

Source

pub fn set_tag<V>(&mut self, key: &str, value: V)
where V: ToString,

Sets a tag to a specific value.

Examples found in repository?
examples/panic-demo.rs (line 13)
3fn main() {
4    let _sentry = sentry::init(
5        sentry::ClientOptions::new()
6            .maybe_release(sentry::release_name!())
7            .debug(true),
8    );
9
10    {
11        let _guard = sentry::Hub::current().push_scope();
12        sentry::configure_scope(|scope| {
13            scope.set_tag("foo", "bar");
14        });
15        panic!("Holy shit everything is on fire!");
16    }
17}
More examples
Hide additional examples
examples/message-demo.rs (line 11)
3fn main() {
4    let _sentry = sentry::init(
5        sentry::ClientOptions::new()
6            .maybe_release(sentry::release_name!())
7            .debug(true),
8    );
9    sentry::configure_scope(|scope| {
10        scope.set_fingerprint(Some(["a-message"].as_ref()));
11        scope.set_tag("foo", "bar");
12    });
13
14    sentry::capture_message("This is recorded as a warning now", sentry::Level::Warning);
15}
examples/send-with-extra.rs (line 14)
3fn main() {
4    let _sentry = sentry::init(
5        sentry::ClientOptions::new()
6            .maybe_release(sentry::release_name!())
7            .debug(true),
8    );
9
10    sentry::with_scope(
11        |scope| {
12            scope.set_level(Some(sentry::Level::Warning));
13            scope.set_fingerprint(Some(["a-message"].as_ref()));
14            scope.set_tag("foo", "bar");
15        },
16        || {
17            panic!("Shit's on fire yo. 🔥 🚒");
18        },
19    );
20}
examples/event-processors.rs (line 23)
3fn main() {
4    let _sentry = sentry::init(
5        sentry::ClientOptions::new()
6            .maybe_release(sentry::release_name!())
7            .debug(true),
8    );
9
10    sentry::configure_scope(|scope| {
11        scope.add_event_processor(|mut event| {
12            event.request = Some(sentry::protocol::Request {
13                url: Some("https://example.com/".parse().unwrap()),
14                method: Some("GET".into()),
15                ..Default::default()
16            });
17            Some(event)
18        });
19    });
20
21    sentry::configure_scope(|scope| {
22        scope.set_fingerprint(Some(["a-message"].as_ref()));
23        scope.set_tag("foo", "bar");
24    });
25
26    let id = sentry::capture_message("An HTTP request failed.", sentry::Level::Error);
27    println!("sent event {id}");
28}
Source

pub fn remove_tag(&mut self, key: &str)

Removes a tag.

If the tag is not set, does nothing.

Source

pub fn set_context<C>(&mut self, key: &str, value: C)
where C: Into<Context>,

Sets a context for a key.

Source

pub fn remove_context(&mut self, key: &str)

Removes a context for a key.

Source

pub fn set_extra(&mut self, key: &str, value: Value)

Sets a extra to a specific value.

Source

pub fn remove_extra(&mut self, key: &str)

Removes a extra.

Source

pub fn add_event_processor<F>(&mut self, f: F)
where F: Fn(Event<'static>) -> Option<Event<'static>> + Send + Sync + RefUnwindSafe + 'static,

Add an event processor to the scope.

Examples found in repository?
examples/event-processors.rs (lines 11-18)
3fn main() {
4    let _sentry = sentry::init(
5        sentry::ClientOptions::new()
6            .maybe_release(sentry::release_name!())
7            .debug(true),
8    );
9
10    sentry::configure_scope(|scope| {
11        scope.add_event_processor(|mut event| {
12            event.request = Some(sentry::protocol::Request {
13                url: Some("https://example.com/".parse().unwrap()),
14                method: Some("GET".into()),
15                ..Default::default()
16            });
17            Some(event)
18        });
19    });
20
21    sentry::configure_scope(|scope| {
22        scope.set_fingerprint(Some(["a-message"].as_ref()));
23        scope.set_tag("foo", "bar");
24    });
25
26    let id = sentry::capture_message("An HTTP request failed.", sentry::Level::Error);
27    println!("sent event {id}");
28}
Source

pub fn add_attachment(&mut self, attachment: Attachment)

Adds an attachment to the scope

Source

pub fn clear_attachments(&mut self)

Clears attachments from the scope

Source

pub fn apply_to_event(&self, event: Event<'static>) -> Option<Event<'static>>

Applies the contained scoped data to fill an event.

Source

pub fn apply_to_transaction(&self, transaction: &mut Transaction<'static>)

Applies the contained scoped data to fill a transaction.

Source

pub fn apply_to_log(&self, log: &mut Log)

Available on crate feature logs only.

Applies the contained scoped data to a log, setting the trace_id and certain default attributes.

Source

pub fn set_span(&mut self, span: Option<TransactionOrSpan>)

Set the given TransactionOrSpan as the active span for this scope.

Examples found in repository?
examples/performance-demo.rs (line 25)
9fn main() {
10    let _sentry = sentry::init(
11        sentry::ClientOptions::new()
12            .maybe_release(sentry::release_name!())
13            .traces_sample_rate(1.0)
14            .debug(true),
15    );
16
17    let transaction =
18        sentry::start_transaction(sentry::TransactionContext::new("transaction", "root span"));
19    let tx_request = Request {
20        url: Some("https://honk.beep".parse().unwrap()),
21        method: Some("GET".to_string()),
22        ..Request::default()
23    };
24    transaction.set_request(tx_request);
25    sentry::configure_scope(|scope| scope.set_span(Some(transaction.clone().into())));
26
27    main_span1();
28
29    thread::sleep(Duration::from_millis(100));
30
31    transaction.finish();
32    sentry::configure_scope(|scope| scope.set_span(None));
33}
34
35fn main_span1() {
36    wrap_in_span("span1", "", || {
37        thread::sleep(Duration::from_millis(50));
38
39        let transaction_ctx = sentry::TransactionContext::continue_from_span(
40            "background transaction",
41            "root span",
42            sentry::configure_scope(|scope| scope.get_span()),
43        );
44        thread::spawn(move || {
45            let transaction = sentry::start_transaction(transaction_ctx);
46            sentry::configure_scope(|scope| scope.set_span(Some(transaction.clone().into())));
47
48            thread::sleep(Duration::from_millis(50));
49
50            thread_span1();
51
52            transaction.finish();
53            sentry::configure_scope(|scope| scope.set_span(None));
54        });
55        thread::sleep(Duration::from_millis(100));
56
57        main_span2()
58    });
59}
60
61fn thread_span1() {
62    wrap_in_span("span1", "", || {
63        thread::sleep(Duration::from_millis(200));
64    })
65}
66
67fn main_span2() {
68    wrap_in_span("span2", "", || {
69        sentry::capture_message(
70            "A message that should have a trace context",
71            sentry::Level::Info,
72        );
73        thread::sleep(Duration::from_millis(200));
74    })
75}
76
77fn wrap_in_span<F, R>(op: &str, description: &str, f: F) -> R
78where
79    F: FnOnce() -> R,
80{
81    let parent = sentry::configure_scope(|scope| scope.get_span());
82    let span1: sentry::TransactionOrSpan = match &parent {
83        Some(parent) => parent.start_child(op, description).into(),
84        None => {
85            let ctx = sentry::TransactionContext::new(description, op);
86            sentry::start_transaction(ctx).into()
87        }
88    };
89    let span_request = Request {
90        url: Some("https://beep.beep".parse().unwrap()),
91        method: Some("GET".to_string()),
92        ..Request::default()
93    };
94    span1.set_request(span_request);
95    sentry::configure_scope(|scope| scope.set_span(Some(span1.clone())));
96
97    let rv = f();
98
99    span1.finish();
100    sentry::configure_scope(|scope| scope.set_span(parent));
101
102    rv
103}
Source

pub fn get_span(&self) -> Option<TransactionOrSpan>

Returns the currently active span.

Examples found in repository?
examples/performance-demo.rs (line 42)
35fn main_span1() {
36    wrap_in_span("span1", "", || {
37        thread::sleep(Duration::from_millis(50));
38
39        let transaction_ctx = sentry::TransactionContext::continue_from_span(
40            "background transaction",
41            "root span",
42            sentry::configure_scope(|scope| scope.get_span()),
43        );
44        thread::spawn(move || {
45            let transaction = sentry::start_transaction(transaction_ctx);
46            sentry::configure_scope(|scope| scope.set_span(Some(transaction.clone().into())));
47
48            thread::sleep(Duration::from_millis(50));
49
50            thread_span1();
51
52            transaction.finish();
53            sentry::configure_scope(|scope| scope.set_span(None));
54        });
55        thread::sleep(Duration::from_millis(100));
56
57        main_span2()
58    });
59}
60
61fn thread_span1() {
62    wrap_in_span("span1", "", || {
63        thread::sleep(Duration::from_millis(200));
64    })
65}
66
67fn main_span2() {
68    wrap_in_span("span2", "", || {
69        sentry::capture_message(
70            "A message that should have a trace context",
71            sentry::Level::Info,
72        );
73        thread::sleep(Duration::from_millis(200));
74    })
75}
76
77fn wrap_in_span<F, R>(op: &str, description: &str, f: F) -> R
78where
79    F: FnOnce() -> R,
80{
81    let parent = sentry::configure_scope(|scope| scope.get_span());
82    let span1: sentry::TransactionOrSpan = match &parent {
83        Some(parent) => parent.start_child(op, description).into(),
84        None => {
85            let ctx = sentry::TransactionContext::new(description, op);
86            sentry::start_transaction(ctx).into()
87        }
88    };
89    let span_request = Request {
90        url: Some("https://beep.beep".parse().unwrap()),
91        method: Some("GET".to_string()),
92        ..Request::default()
93    };
94    span1.set_request(span_request);
95    sentry::configure_scope(|scope| scope.set_span(Some(span1.clone())));
96
97    let rv = f();
98
99    span1.finish();
100    sentry::configure_scope(|scope| scope.set_span(parent));
101
102    rv
103}
Source

pub fn iter_trace_propagation_headers( &self, ) -> impl Iterator<Item = (&'static str, String)>

Returns the headers needed for distributed tracing.

Trait Implementations§

Source§

impl Clone for Scope

Source§

fn clone(&self) -> Scope

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Scope

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
Source§

impl Default for Scope

Source§

fn default() -> Scope

Returns the “default value” for a type. Read more

Auto Trait Implementations§

§

impl Freeze for Scope

§

impl RefUnwindSafe for Scope

§

impl Send for Scope

§

impl Sync for Scope

§

impl Unpin for Scope

§

impl UnsafeUnpin for Scope

§

impl UnwindSafe for Scope

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> FromRef<T> for T
where T: Clone,

Source§

fn from_ref(input: &T) -> T

Converts to this type from a reference to the input type.
Source§

impl<T> FutureExt for T

Source§

fn with_context(self, otel_cx: Context) -> WithContext<Self>

Attaches the provided Context to this type, returning a WithContext wrapper. Read more
Source§

fn with_current_context(self) -> WithContext<Self>

Attaches the current Context to this type, returning a WithContext wrapper. Read more
Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

Source§

impl<T> SendSyncUnwindSafe for T
where T: Send + Sync + UnwindSafe + ?Sized,

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more