[][src]Crate tracing_error

Utilities for enriching error handling with tracing diagnostic information.

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:

Note: This crate is currently experimental.

Compiler support: requires rustc 1.39+

Feature Flags

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 ...
    }
}

impl Error for MyError {}

impl MyError {
    pub fn new() -> Self {
        Self {
            context: SpanTrace::capture(),
            // ... other error information ...
        }
    }
}

This crate also provides the InstrumentResult and InstrumentError traits, which can be used to wrap errors with a TracedError which bundles the inner error with a SpanTrace.

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 3 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 ErrorLayer and add it to their Subscriber in order to enable capturing SpanTraces. For example:

use tracing_error::ErrorLayer;
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 `ErrorLayer`...
        .with(ErrorLayer::default());

    // set the subscriber as the default for the application
    tracing::subscriber::set_global_default(subscriber);
}

Modules

preludefeature="traced-error"

The tracing-error prelude.

Structs

ErrorLayer

A subscriber Layer that enables capturing SpanTraces.

SpanTrace

A captured trace of tracing spans.

SpanTraceStatus

The current status of a SpanTrace, indicating whether it was captured or whether it is empty for some other reason.

TracedErrorfeature="traced-error"

A wrapper type for Errors that bundles a SpanTrace with an inner Error type.

Traits

ExtractSpanTracefeature="traced-error"

A trait for extracting SpanTraces created by in_current_span() from dyn Error trait objects

InstrumentErrorfeature="traced-error"

Extension trait for instrumenting errors with SpanTraces

InstrumentResultfeature="traced-error"

Extension trait for instrumenting errors in Results with SpanTraces