## Motivation
Currently, the `tracing-subscriber` crate has the `MakeWriter` trait for
customizing the io writer used by `fmt`. This trait is necessary (rather
than simply using a `Write` instance) because the default implementation
performs the IO on the thread where an event was recorded, meaning that
a separate writer needs to be acquired by each thread (either by calling
a function like `io::stdout`, by locking a shared `Write` instance,
etc).
Right now there is a blanket impl for `Fn() -> T where T: Write`. This
works fine with functions like `io::stdout`. However, the _other_ common
case for this trait is locking a shared writer.
Therefore, it makes sense to see an implementation like this:
``` rust
impl<'a, W: io::Write> MakeWriter for Mutex<W>
where
W: io::Write,
{
type Writer = MutexWriter<'a, W>;
fn make_writer(&self) -> Self::Writer {
MutexWriter(self.lock().unwrap())
}
}
pub struct MutexWriter<'a, W>(MutexGuard<'a, W>);
impl<W: io::Write> io::Write for MutexWriter<'_, W> {
// write to the shared writer in the `MutexGuard`...
}
```
Unfortunately, it's impossible to write this. Since `MakeWriter` always
takes an `&self` parameter and returns `Self::Writer`, the generic
parameter is unbounded:
```
Checking tracing-subscriber v0.2.4 (/home/eliza/code/tracing/tracing-subscriber)
error[E0207]: the lifetime parameter `'a` is not constrained by the impl trait, self type, or predicates
--> tracing-subscriber/src/fmt/writer.rs:61:6
|
61 | impl<'a, W: io::Write> MakeWriter for Mutex<W>
| ^^ unconstrained lifetime parameter
error: aborting due to previous error
```
This essentially precludes any `MakeWriter` impl where the writer is
borrowed from the type implementing `MakeWriter`. This is a significant
blow to the usefulness of the trait. For example, it prevented the use
of `MakeWriter` in `tracing-flame` as suggested in
https://github.com/tokio-rs/tracing/pull/631#discussion_r391138233.
## Proposal
This PR changes `MakeWriter` to be generic over a lifetime `'a`:
```rust
pub trait MakeWriter<'a> {
type Writer: io::Write;
fn make_writer(&'a self) -> Self::Writer;
}
```
The `self` parameter is now borrowed for the `&'a` lifetime, so it is
okay to return a writer borrowed from `self`, such as in the `Mutex`
case.
I've also added an impl of `MakeWriter` for `Mutex<T> where T: Writer`.
Unfortunately, this is a breaking change and will need to wait until we
release `tracing-subscriber` 0.3.
Fixes #675.
Signed-off-by: Eliza Weisman <eliza@buoyant.io>
tracing-error
Utilities for enriching error handling with tracing diagnostic
information.
Documentation (release) | Documentation (master) | Chat
Overview
tracing is a framework for instrumenting Rust programs to collect
scoped, structured, and async-aware diagnostics. This crate provides
integrations between tracing instrumentation and Rust error handling. It
enables enriching error types with diagnostic information from tracing
span contexts, formatting those contexts when errors are displayed, and
automatically generate tracing events when errors occur.
The crate provides the following:
-
SpanTrace, a captured trace of the currenttracingspan context -
ErrorSubscriber, a subscriber layer which enables capturingSpanTraces
Note: This crate is currently experimental.
Compiler support: requires rustc 1.42+
Usage
tracing-error provides the SpanTrace type, which captures the current
tracing span context when it is constructed and allows it to be displayed
at a later time.
For example:
use std::{fmt, error::Error};
use tracing_error::SpanTrace;
#[derive(Debug)]
pub struct MyError {
context: SpanTrace,
// ...
}
impl fmt::Display for MyError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
// ... format other parts of the error ...
self.context.fmt(f)?;
// ... format other error context information, cause chain, etc ...
# Ok(())
}
}
impl Error for MyError {}
impl MyError {
pub fn new() -> Self {
Self {
context: SpanTrace::capture(),
// ... other error information ...
}
}
}
This crate also provides TracedError, for attaching a SpanTrace to an
existing error. The easiest way to wrap errors in TracedError is to either
use the InstrumentResult and InstrumentError traits or the From/Into
traits.
use tracing_error::prelude::*;
std::fs::read_to_string("myfile.txt").in_current_span()?;
Once an error has been wrapped with with a TracedError, the SpanTrace
can be extracted one of three ways: either via TracedError's
Display/Debug implementations, or via the ExtractSpanTrace trait.
For example, here is how one might print the errors but specialize the
printing when the error is a placeholder for a wrapping SpanTrace:
use std::error::Error;
use tracing_error::ExtractSpanTrace as _;
fn print_extracted_spantraces(error: &(dyn Error + 'static)) {
let mut error = Some(error);
let mut ind = 0;
eprintln!("Error:");
while let Some(err) = error {
if let Some(spantrace) = err.span_trace() {
eprintln!("found a spantrace:\n{}", spantrace);
} else {
eprintln!("{:>4}: {}", ind, err);
}
error = err.source();
ind += 1;
}
}
Whereas here, we can still display the content of the SpanTraces without
any special casing by simply printing all errors in our error chain.
use std::error::Error;
fn print_naive_spantraces(error: &(dyn Error + 'static)) {
let mut error = Some(error);
let mut ind = 0;
eprintln!("Error:");
while let Some(err) = error {
eprintln!("{:>4}: {}", ind, err);
error = err.source();
ind += 1;
}
}
Applications that wish to use tracing-error-enabled errors should
construct an ErrorSubscriber and add it to their Subscriber in order to
enable capturing SpanTraces. For example:
use tracing_error::ErrorSubscriber;
use tracing_subscriber::prelude::*;
fn main() {
let subscriber = tracing_subscriber::Registry::default()
// any number of other subscriber layers may be added before or
// after the `ErrorSubscriber`...
.with(ErrorSubscriber::default());
// set the subscriber as the default for the application
tracing::subscriber::set_global_default(subscriber);
}
Feature Flags
traced-error- Enables theTracedErrortype and related traitsInstrumentResultandInstrumentErrorextension traits, which provide anin_current_span()method for bundling errors with aSpanTrace.ExtractSpanTraceextension trait, for extractingSpanTraces from behinddyn Errortrait objects.
Supported Rust Versions
Tracing is built against the latest stable release. The minimum supported version is 1.42. The current Tracing version is not guaranteed to build on Rust versions earlier than the minimum supported version.
Tracing follows the same compiler support policies as the rest of the Tokio project. The current stable Rust compiler and the three most recent minor versions before it will always be supported. For example, if the current stable compiler version is 1.45, the minimum supported version will not be increased past 1.42, three minor versions prior. Increasing the minimum supported compiler version is not considered a semver breaking change as long as doing so complies with this policy.
Related Crates
In addition to this repository, here are also several third-party crates which
are not maintained by the tokio project. These include:
color-spantraceprovides a formatter for rendering SpanTrace in the style ofcolor-backtracecolor-eyreprovides a customized version ofeyre::Reportfor capturing span traces and backtraces with new errors and pretty printing them in error reports.
License
This project is licensed under the MIT license.
Contribution
Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in Tracing by you, shall be licensed as MIT, without any additional terms or conditions.