hyper_trace_id/
lib.rs

1#[cfg(feature = "axum")]
2mod extract;
3
4mod layer;
5
6pub use crate::layer::SetTraceIdLayer;
7use std::fmt::{Display, Formatter};
8use uuid::Uuid;
9
10/// Make a type usable as trace id.
11///
12/// ```
13/// use std::fmt::{Display, Formatter};
14/// use hyper_trace_id::MakeTraceId;
15/// use uuid::Uuid;
16///
17/// #[derive(Clone)]
18/// struct MyTraceId {
19///     id: String,
20/// }
21///
22/// impl Display for MyTraceId {
23///     fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
24///         write!(f, "{}", self.id)
25///     }
26/// }
27///
28/// impl MakeTraceId for MyTraceId {
29///     fn make_trace_id() -> Self {
30///         Self {
31///             id: Uuid::new_v4().to_string()
32///         }
33///     }
34/// }
35/// ```
36pub trait MakeTraceId: Send + Sync + Display + Clone {
37    fn make_trace_id() -> Self;
38}
39
40impl MakeTraceId for String {
41    fn make_trace_id() -> Self {
42        Uuid::new_v4().to_string()
43    }
44}
45
46#[derive(Debug, Clone)]
47pub struct TraceId<T>
48where
49    T: MakeTraceId,
50{
51    pub id: T,
52}
53
54impl<T> TraceId<T>
55where
56    T: MakeTraceId,
57{
58    pub(crate) fn new() -> Self {
59        TraceId {
60            id: T::make_trace_id(),
61        }
62    }
63}
64
65impl<T> Display for TraceId<T>
66where
67    T: MakeTraceId,
68{
69    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
70        write!(f, "{}", self.id)
71    }
72}