1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
// Copyright 2022 IOTA Stiftung
// SPDX-License-Identifier: Apache-2.0

use tracing::trace_span;
use tracing_futures::{Instrument, Instrumented};

/// The field name of the [`Span`](tracing::Span) location file.
pub(crate) const FILE_FIELD_NAME: &str = "loc.file";

/// The field name of the [`Span`](tracing::Span) location line.
pub(crate) const LINE_FIELD_NAME: &str = "loc.line";

/// The target of the wrapping [`Span`](tracing::Span).
pub const SPAN_TARGET: &str = "trace_tools::observe";

/// The name of the wrapping [`Span`](tracing::Span).
pub const SPAN_NAME: &str = "observed";

/// Instruments a future with a `tracing` span.
///
/// This span is given the `trace_tools::observe` target, so that it can be more easily filtered
/// in any subscribers or subscriber layers. It also records the future's calling location
/// in its fields.
pub trait Observe: Sized {
    #[track_caller]
    /// Instruments `Self` with a `tracing` span, returning [`Instrumented<Self>`].
    fn observe(self, name: &str) -> Instrumented<Self>;
}

impl<T: Instrument> Observe for T {
    #[track_caller]
    fn observe(self, name: &str) -> Instrumented<Self> {
        let location = std::panic::Location::caller();

        let span = trace_span!(
            target: SPAN_TARGET,
            SPAN_NAME,
            observed.name = name,
            loc.file = location.file(),
            loc.line = location.line(),
            loc.col = location.column(),
        );

        self.instrument(span)
    }
}