Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
T

tracing

> DevOps
Open source

Application level tracing for Rust.

6.8K stars0 likes0 views
WebsiteGitHub

About

Application level tracing for Rust.

Tracing — Structured, application-level diagnostics

Crates.io Documentation Documentation (v0.2.x) MIT licensed Build Status Discord chat

Website | Chat

Overview

tracing is a framework for instrumenting Rust programs to collect structured, event-based diagnostic information. tracing is maintained by the Tokio project, but does not require the tokio runtime to be used.

Branch set-up

  • main - Default branch, crates.io releases are done from this branch. This was previously the v0.1.x branch.
  • v0.2.x - Branch containing the as-yet unreleased 0.2 version of tracing-core, tracing, and all the other tracing crates that depend on these versions. This was previously the master branch.

Usage

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 a subscriber for logging traces with reasonable defaults. Additionally, tracing-subscriber is able to consume messages emitted by log-instrumented libraries and modules.

To use tracing-subscriber, add the following to your Cargo.toml:

toml
[dependencies]
tracing = "0.1"
tracing-subscriber = "0.3"

Then create and install a Subscriber, for example using init():

rust
use tracing::info;
use tracing_subscriber;

fn main() {
    // install global subscriber configured based on RUST_LOG envvar.
    tracing_subscriber::fmt::init();

    let number_of_yaks = 3;
    // this creates a new event, outside of any spans.
    info!(number_of_yaks, "preparing to shave yaks");

    let number_shaved = yak_shave::shave_all(number_of_yaks);
    info!(
        all_yaks_shaved = number_shaved == number_of_yaks,
        "yak shaving completed."
    );
}

Using init() calls set_global_default() so 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.

For more control, a subscriber can be built in stages and not set globally, but instead used to locally override the default subscriber. For example:

rust
use tracing::{info, Level};
use tracing_subscriber;

fn main() {
    let subscriber = tracing_subscriber::fmt()
        // filter spans/events with level TRACE or higher.
        .with_max_level(Level::TRACE)
        // build but do not install the subscriber.
        .finish();

    tracing::subscriber::with_default(subscriber, || {
        info!("This will be logged to stdout");
    });
    info!("This will _not_ be logged to stdout");
}

Any trace events generated outside the context of a subscriber will not be collected.

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.

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.

…
toml
[dependencies]
tracing = "0.1"

Note: Libraries should NOT install a subscriber by using a method that calls set_global_default(), as this will cause conflicts when executables try to set the default later.

In Asynchronous Code

To trace async fns, the preferred method is using the #[instrument] attribute:

rust
use tracing::{info, instrument};
use tokio::{io::AsyncWriteExt, net::TcpStream};
use std::io;

#[instrument]
async fn write(stream: &mut TcpStream) -> io::Result<usize> {
    let result = stream.write(b"hello world\n").await;
    info!("wrote to stream; success={:?}", result.is_ok());
    result
}

Special handling is needed for the general case of code using std::future::Future or blocks with async/await, as the following example will not work:

rust
async {
    let _s = span.enter();
    // ...
}

The span guard _s will not exit until the future generated by the async block is complete. Since futures and spans can be entered and exited multiple times without them completing, the span remains entered for as long as the future exists, rather than being entered only when it is polled, leading to very confusing and incorrect output. For more details, see the documentation on closing spans.

This problem can be solved using the Future::instrument combinator:

rust
use tracing::Instrument;

let my_future = async {
    // ...
};

my_future
    .instrument(tracing::info_span!("my_future"))
    .await

Future::instrument attaches a span to the future, ensuring that the span's lifetime is as long as the future's.

Under the hood, the #[instrument] macro performs the same explicit span attachment that Future::instrument does.

Supported Rust Versions

Tracing is built against the latest stable release. The minimum supported version is 1.65. 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.69, the minimum supported version will not be increased past 1.66, 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.

Getting Help

First, see if the answer to your question can be found in the API documentation. If the answer is not there, there is an active community in the Tracing Discord channel. We would be happy to try to answer your question. Last, if that doesn't work, try opening an issue with the question.

Contributing

:balloon: Thanks for your help improving the project! We are so happy to have you! We have a contributing guide to help you get involved in the Tracing project.

Project layout

The tracing crate contains the primary instrumentation API, used for instrumenting libraries and applications to emit trace data. The tracing-core crate contains the core API primitives on which the rest of tracing is instrumented. Authors of trace subscribers may depend on tracing-core, which guarantees a higher level of stability.

Additionally, this repository contains several compatibility and utility libraries built on top of tracing. Some of these crates are in a pre-release state, and are less stable than the tracing and tracing-core crates.

The crates included as part of Tracing are:

  • tracing-futures: Utilities for instrumenting futures. (crates.io|docs)

  • tracing-macros: Experimental macros for emitting trace events (unstable).

  • tracing-attributes: Procedural macro attributes for automatically instrumenting functions. (crates.io|docs)

  • tracing-log: Compatibility with the log crate (unstable).

  • tracing-serde: A compatibility layer for serializing trace data with serde (unstable).

  • tracing-subscriber: Subscriber implementations, and utilities for implementing and composing Subscribers. (crates.io|docs)

  • tracing-tower: Compatibility with the tower ecosystem (unstable).

  • tracing-appender: Utilities for outputting tracing data, including a file appender and non-blocking writer. (crates.io|docs)

  • tracing-error: Provides SpanTrace, a type for instrumenting errors with tracing spans. (crates.io|docs)

  • tracing-flame: Provides a layer for generating flame graphs based on tracing span entry / exit events. (crates.io|docs)

  • tracing-journald: Provides a layer for recording events to the Linux journald service, preserving structured data. (crates.io|docs)

Related Crates

In addition to this repository, here are also several third-party crates which are not maint

Issues· 892 open

View all issuesOpen on GitHub
  • #3582

    Handle `syn` v3

    Updated Sep 21, 2026
  • #3511

    Panic in pretty formatter

    Updated Sep 20, 2026
  • #3613

    Get all dependencies to syn v3

    Updated Sep 18, 2026
  • #3611

    has_just_one callsite short-path caches Interest::Never when a subscriber-less thread first registers the callsite

    Updated Sep 16, 2026
  • #2874

    Incorrect `Interest::Never` is cached and never invalidated on v0.1

    Updated Sep 16, 2026
  • #3612

    "Error reading the log directory/files" always fires the first time

    Updated Sep 16, 2026
  • #3599

    tracing-appender has broken symlinks when a relative path is specified

    Updated Sep 10, 2026
  • #3607

    Make `Span` `#[must_use]`

    Updated Sep 8, 2026
  • #3518

    Documentation mentions non-existent `time` crate feature

    Updated Aug 31, 2026
  • #3601

    RUSTSEC-2026-0258: h2 unbounded empty DATA frames

    Updated Aug 19, 2026

> Tags

Rustdiagnosticslogginglogging-and-metricslogging-facade

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 23, 2026
CategoryDevOps
PricingOpen source

> Related tools

D
Docker
容器化平台,标准化应用交付
G
GitHub Actions
GitHub 原生 CI/CD 工作流
N
Nginx
高性能 Web 服务器与反向代理