tracing_helpers/
lib.rs

1// Copyright (c) Microsoft Corporation.
2// Licensed under the MIT License.
3
4//! Helpers for using the tracing crate more effectively.
5//!
6//! In particular, this includes extension traits to make it easier to pass
7//! errors to tracing events. The events can take a `dyn Error`, but getting a
8//! `dyn Error` from an arbitrary error type requires casting.
9//!
10//! Hopefully this crate will be short lived as `tracing` ergonomics continue
11//! to improve.
12
13pub mod formatter;
14
15/// Extension trait to make it easy to trace anyhow errors.
16pub trait AnyhowValueExt {
17    /// Returns the error as a type that can be traced.
18    fn as_error(&self) -> &(dyn 'static + std::error::Error);
19}
20
21impl AnyhowValueExt for anyhow::Error {
22    fn as_error(&self) -> &(dyn 'static + std::error::Error) {
23        &**self
24    }
25}
26
27/// Extension trait to make it easy to trace errors.
28pub trait ErrorValueExt {
29    /// Returns the error as a type that can be traced.
30    fn as_error(&self) -> &(dyn 'static + std::error::Error);
31}
32
33impl<T> ErrorValueExt for T
34where
35    T: 'static + std::error::Error,
36{
37    fn as_error(&self) -> &(dyn 'static + std::error::Error) {
38        self
39    }
40}