timeout_tracing/
trace.rs

1use std::{backtrace::Backtrace, fmt::Display};
2
3use tracing_error::SpanTrace;
4
5/// A trait to support custom implementations of traces
6pub trait CaptureTrace {
7    /// Representation for captured trace
8    type Trace;
9    /// Capture trace at the current moment.
10    fn capture(&self) -> Self::Trace;
11}
12
13/// Implementation of [`CaptureTrace`] that captures span trace using [`tracing_error::SpanTrace`].
14/// [`tracing`] must be initialized with [`tracing_error::ErrorLayer`] for the trace to be captured successfully.
15pub struct CaptureSpanTrace;
16
17impl CaptureTrace for CaptureSpanTrace {
18    type Trace = SpanTrace;
19
20    fn capture(&self) -> Self::Trace {
21        SpanTrace::capture()
22    }
23}
24
25/// Implementation of [`CaptureTrace`] that captures both a span trace using [`tracing_error::SpanTrace`]
26/// and a stack trace.
27/// [`tracing`] must be initialized with [`tracing_error::ErrorLayer`] for the span trace to be captured successfully
28/// and `RUST_BACKTRACE` environment variable must be set for the stack trace to be captured.
29pub struct CaptureSpanAndStackTrace;
30
31impl CaptureTrace for CaptureSpanAndStackTrace {
32    type Trace = StackAndSpanTrace;
33
34    fn capture(&self) -> Self::Trace {
35        StackAndSpanTrace::capture()
36    }
37}
38
39#[derive(Debug)]
40pub struct StackAndSpanTrace {
41    pub(crate) stack_trace: Backtrace,
42    pub(crate) span_trace: SpanTrace,
43}
44
45impl StackAndSpanTrace {
46    pub(crate) fn capture() -> Self {
47        Self {
48            span_trace: SpanTrace::capture(),
49            stack_trace: Backtrace::capture(),
50        }
51    }
52
53    pub fn stack_trace(&self) -> &Backtrace {
54        &self.stack_trace
55    }
56
57    pub fn span_trace(&self) -> &SpanTrace {
58        &self.span_trace
59    }
60}
61
62impl Display for StackAndSpanTrace {
63    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
64        write!(
65            f,
66            "span trace:\n{span_trace}\nstack trace:\n{stack_trace}",
67            span_trace = self.span_trace,
68            stack_trace = self.stack_trace,
69        )
70    }
71}