tracing
Application-level tracing for Rust.
Overview
tracing is a framework for instrumenting Rust programs to collect
structured, event-based diagnostic information.
In asynchronous systems like Tokio, interpreting traditional log messages can
often be quite challenging. Since individual tasks are multiplexed on the same
thread, associated events and log lines are intermixed making it difficult to
trace the logic flow. tracing expands upon logging-style diagnostics by
allowing libraries and applications to record structured events with additional
information about temporality and causality — unlike a log message, a span
in tracing has a beginning and end time, may be entered and exited by the
flow of execution, and may exist within a nested tree of similar spans. In
addition, tracing spans are structured, with the ability to record typed
data as well as textual messages.
The tracing crate provides the APIs necessary for instrumenting libraries
and applications to emit trace data.
Compiler support: requires rustc 1.39+
Usage
(The examples below are borrowed from the log crate's yak-shaving
example, modified to
idiomatic tracing.)
In Applications
In order to record trace events, executables have to use a Subscriber
implementation compatible with tracing. A Subscriber implements a way of
collecting trace data, such as by logging it to standard output. tracing_subscriber's
fmt module provides reasonable defaults.
Additionally, tracing-subscriber is able to consume messages emitted by log-instrumented libraries and modules.
The simplest way to use a subscriber is to call the set_global_default function.
use ;
use FmtSubscriber;
[]
= "0.1"
= "0.2.0-alpha.4"
This subscriber will be used as the default in all threads for the remainder of the duration
of the program, similar to how loggers work in the log crate.
In addition, you can locally override the default subscriber. For example:
use ;
use FmtSubscriber;
This approach allows trace data to be collected by multiple subscribers within different contexts in the program. Note that the override only applies to the currently executing thread; other threads will not see the change from with_default.
Any trace events generated outside the context of a subscriber will not be collected.
Once a subscriber has been set, instrumentation points may be added to the
executable using the tracing crate's macros.
In Libraries
Libraries should only rely on the tracing crate and use the provided macros
and types to collect whatever information might be useful to downstream consumers.
use ;
use ;
// the `#[tracing::instrument]` attribute creates and enters a span
// every time the instrumented function is called. The span is named after the
// the function or method. Paramaters passed to the function are recorded as fields.