Tracing

tracing is a framework for instrumenting Rust programs to collect structured, event-based diagnostic information. It is alternative to the older log crate and has adapters to be backwards compatible.

To enable tracing in your application, add the following crates to your project:

cargo add tracing tracing-subscriber

For libraries, tracing-subscriber is usually not required.

Log messages to the console

tracing-badge tracing-subscriber-badge cat-debugging-badge

The tracing crate provides macros to emit log events to a tracing subscriber. The tracing-subscriber crate configures where to send the events. To install the default tracing subscriber, call tracing_subscriber::fmt::init().

use tracing::{debug, error, info, trace, warn};

fn main() {
    tracing_subscriber::fmt::init();

    error!("This is an error!");
    warn!("This is a warning.");
    info!("This is an informational message.");

    // with the default configuration, debug! and trace! messages are not shown
    debug!("This is a debug message.");
    trace!("This is a trace message.");
}

#[test]
fn test_main() {
    main();
}

The default log level is INFO. Tracing will drop events logged at lower levels. Running this code prints the following to the console:

2024-12-01T07:56:14.778440Z ERROR tracing_console: This is an error!
2024-12-01T07:56:14.778568Z  WARN tracing_console: This is a warning.
2024-12-01T07:56:14.778596Z  INFO tracing_console: This is an informational message.

To configure a more verbose default level, set the RUST_LOG environment variable:

RUST_LOG=trace cargo run --example log-debug

Cargo prints these following extra lines in addition to the ones above:

2024-12-01T07:56:14.778613Z DEBUG tracing_console: This is a debug message.
2024-12-01T07:56:14.778640Z TRACE tracing_console: This is a trace message.