Module tracing_forest::tag

source ·
Expand description

Supplement events with categorical information.

Use cases for tags

Using tags in trace data can improve readability by distinguishing between different kinds of trace data such as requests, internal state, or special operations. An error during a network request could mean a timeout occurred, while an error in the internal state could mean corruption. Both are errors, but one should be treated more seriously than the other, and therefore the two should be easily distinguishable.

How to use tags

Every application has its own preferences for how events should be tagged, and this can be set via a custom TagParser in the ForestLayer. This works by passing a reference to each incoming [Event] to the TagParser, which can then be parsed into an Option<Tag> for the ForestLayer to use later.

Since TagParser is blanket implemented for all Fn(&Event) -> Option<Tag> the easiest way to create one is to define a top-level function with this type signature.

Once the function is defined, it can either be passed directly to ForestLayer::new, or can be passed to Builder::set_tag.

Examples

Declaring and using a custom TagParser.

use tracing_forest::{util::*, Tag};

fn simple_tag(event: &Event) -> Option<Tag> {
    let target = event.metadata().target();
    let level = *event.metadata().level();

    Some(match target {
        "security" if level == Level::ERROR => Tag::builder()
            .prefix(target)
            .suffix("critical")
            .icon('🔐')
            .build(),
        "admin" | "request" => Tag::builder().prefix(target).level(level).build(),
        _ => return None,
    })
}

#[tokio::main]
async fn main() {
    tracing_forest::worker_task()
        .set_tag(simple_tag)
        .build()
        .on(async {
            // Since `simple_tag` reads from the `target`, we use the target.
            // If it parsed the event differently, we would reflect that here.
            info!(target: "admin", "some info for the admin");
            error!(target: "request", "the request timed out");
            error!(target: "security", "the db has been breached");
            info!("no tags here");
        })
        .await;
}
INFO     i [admin.info]: some info for the admin
ERROR    🚨 [request.error]: the request timed out
ERROR    🔐 [security.critical]: the db has been breached
INFO     i [info]: no tags here

Structs

  • Incrementally construct Tags.
  • A type used by Builder to indicate that the icon has been set.
  • A TagParser that always returns None.
  • A type used by Builder to indicate that the suffix has been set.
  • A basic Copy type containing information about where an event occurred.

Traits