Tracing and Observability: Seeing Inside Tokio
6 min read
Welcome to the X-Ray vision department of async programming! 🩻
If you have been using println! to debug your asynchronous Tokio applications, you have likely realized something terrifying: Time is not linear here.
In synchronous programming, logs appear in order. In async programming, multiple tasks are paused, resumed, and shuffled across threads. A println! from Task A might appear right in the middle of a log from Task B. It’s like trying to read three different books simultaneously, line by line, while someone shuffles the pages.
Today, we ditch the "printf debugging" and adopt Structured Observability.
1. The tracing Crate Ecosystem: Beyond Basic Println!
The Problem
The standard log crate in Rust is great for synchronous code, but it lacks context. It generates unstructured text. It tells you what happened, but it struggles to tell you where in the async execution flow it happened, or which task caused it.
The Solution
The tracing crate is a framework for instrumenting Rust programs to collect structured, event-based diagnostic information. It is built specifically with async runtimes (like Tokio) in mind.
Unlike log, tracing understands that a unit of work (like a request) has a start, an end, and happens within a specific context.
The Ecosystem
The tracing ecosystem is split into two main parts (separation of concerns):
tracing(The API): Libraries and app code use this to say "I am doing X". It is extremely lightweight.tracing-subscriber(The Collector): The application binary uses this to say "Here is how I want to record X" (print to stdout, send to a file, send to Datadog/Jaeger).
🛠️ Getting Started: The Setup
Let's get the industry-standard boilerplate ready. You need the core library and the standard subscriber.
Cargo.toml
[dependencies]
tokio = { version = "1", features = ["full"] }
tracing = "0.1"
tracing-subscriber = "0.3"💡 Fun Fact: The
tracingcrate was originally designed by the Tokio team because they literally couldn't debug their own runtime without it. If the creators of the matrix needed it, you do too.
2. Spans and Events: Tracking Execution Context
Before we write code, we must define the atoms of tracing.
Events
Definition: An Event is a point in time. It represents something that happened at a specific instant.
This is closest to log::info! or println!.
- "Connection received."
- "Database query failed."
Spans
Definition: A Span represents a period of time with a beginning and an end. Spans can have parents and children, forming a tree.
This is the magic glue for async. A span represents a unit of work (like "Handling User Login"). Even if the task pauses (awaits) and another task runs, the Span remains logically active for that context.
The Interaction
When an Event occurs, it happens inside a Span.
Visualizing the difference:
Without Spans:
text[Info] Start Request A [Info] Start Request B [Info] Database Result (Who owns this? A or B?) [Info] Sending Response (For A or B?)With Spans:
textSpan(Request A) { [Info] Start [Info] Database Result Span(Process Data) { [Info] Calculation done } [Info] Sending Response } Span(Request B) { ... }
Hands-on Code
Here is how you manually create spans and events.
use tracing::{info, error, span, Level};
#[tokio::main]
async fn main() {
// We will setup the subscriber in the next section,
// imagine it's here for now!
// Create a span
let span = span!(Level::INFO, "my_span", user_id = "42");
// "Enter" the span.
// The guard (_enter) keeps the span active until it is dropped.
let _enter = span.enter();
// This event is now associated with "my_span" and "user_id=42"
info!("Starting the connection sequence");
// Do some work...
// _enter is dropped here, closing the span.
}3. Instrumenting Async Functions and Blocks
The Problem
Manually creating spans, entering them, and managing the _enter guard logic in async functions is tricky. In async Rust, when you .await, the function yields execution. If you aren't careful, you might "exit" the span context while the future is waiting, losing your trace ID.
The Solution: #[instrument]
The tracing crate provides a procedural macro called #[instrument]. It handles all the heavy lifting.
- It creates a Span with the function's name.
- It captures all function arguments as fields (automatically logging them!).
- It attaches the span to the
Future, ensuring that every time the Future wakes up, the Span is re-entered correctly.
Practical Example
use tracing::{info, instrument};
// 1. This macro automatically creates a span named "fetch_data"
// 2. It automatically logs "url" because it's an argument.
#[instrument]
async fn fetch_data(url: String) {
info!("Connecting to remote server..."); // This log inherits context
// Simulate network delay
tokio::time::sleep(tokio::time::Duration::from_millis(100)).await;
info!("Data received!");
}
#[tokio::main]
async fn main() {
// Initialize subscriber (Standard boilerlate)
tracing_subscriber::fmt::init();
let url = "https://api.freecodecamp.org".to_string();
fetch_data(url).await;
}Output (Formatted):
INFO fetch_data{url="https://api.freecodecamp.org"}: connect: Connecting to remote server...
INFO fetch_data{url="https://api.freecodecamp.org"}: connect: Data received!⚠️ Industry Best Practice: The skip field
By default, #[instrument] prints every argument. If you pass a 5MB JSON blob or a struct containing a password, it will get logged. Bad idea.
Use skip to ignore sensitive or large arguments.
struct DatabaseConnection; // Pretend this is big
#[instrument(skip(db_conn, password))]
async fn login_user(db_conn: &DatabaseConnection, user: String, password: &str) {
info!("Attempting login");
// Logs: login_user{user="Alice"}: Attempting login
// Does NOT log db_conn or password.
}4. Integrating with Subscribers: Formatting and Exporting Logs
The Problem
You have instrumented your code, but if you run it now, you'll see... nothing. tracing is lazy. It generates data, but it needs a Subscriber to actually record it.
The Solution: tracing-subscriber
This crate provides the standard way to collect traces.
Basic Setup (Stdout)
The fmt subscriber prints to the console. This is what you use for local development.
fn main() {
// Simplest setup:
tracing_subscriber::fmt::init();
// ... app logic
}Advanced Setup: Filtering with EnvFilter
In production, you don't want to log DEBUG or TRACE levels (too much noise/cost). You want to control this via Environment Variables without recompiling code.
The boilerplate you will use 99% of the time:
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};
fn main() {
tracing_subscriber::registry()
.with(
tracing_subscriber::fmt::layer()
// Make it look pretty for humans
.with_target(false) // Hides the module path if you want cleaner logs
.compact() // Compact formatting
)
.with(
// Read RUST_LOG env var, fallback to "info" if not set
tracing_subscriber::EnvFilter::try_from_default_env()
.unwrap_or_else(|_| "info".into())
)
.init();
tracing::info!("System initialized");
}How to run it:
# Shows Info, Warn, Error
cargo run
# Shows Debug logs specifically for your crate, info for others
RUST_LOG=my_app=debug,tokio=info cargo runJSON Formatting (Machine Readable)
For production systems using Logstash, Datadog, or Splunk, human-readable text is hard to parse. You want JSON.
tracing_subscriber::fmt()
.json() // <--- The magic switch
.init();Output:
{"timestamp":"2023-10-01T12:00:00Z","level":"INFO","message":"Data received!","url":"https://...","span":{"name":"fetch_data"}}📝 Summary: The Mental Model
- Events are dots on a timeline.
- Spans are the buckets that hold those dots (context).
#[instrument]is the macro that automates Spans for async functions.- Subscribers represent the eyes/ears that record the data.
tracingallows you to reconstruct the story of a request as it hops between threads.
📚 References & Further Reading
Now go forth and illuminate your async code! No more stumbling in the dark with println!. 🕯️
Challenge
Your Task
Instrument a mock asynchronous service function using the tracing ecosystem to produce structured, filterable, JSON-formatted logs.
Requirements
- In the
process_user_datafunction, use the#[instrument]macro to automatically create a span for the function's execution. - The
UserDatastruct contains a sensitiveauth_token. Configure the#[instrument]macro to skip this field, preventing it from appearing in logs. - Inside
process_user_data, after the firstawait, create a new, manual child span with the following properties:- Name:
"db_interaction" - Level:
INFO - Target:
"database" - Fields:
db.system = "postgres"anddb.statement = "UPDATE users..."
- Name:
- Within the scope of the
"db_interaction"span, create a singleINFOlevel event with the message"Database update successful"and a fieldrows_affected = 1. - In the
mainfunction, initialize and set a global subscriber. This subscriber must be built using layers (.with(...)) and configured to:- Use an
EnvFilterto show logs from theuser_servicetarget at theinfolevel and above. - Use a formatting layer that outputs all trace data as JSON to standard output.
- Use an
Complete the // TODO sections in the provided code to meet these requirements.
Expected result
Your code should correctly implement the tracing instrumentation and subscriber setup as requested. The final code should look similar to the following, with all TODOs completed:
use tracing::{instrument, Level, event, span};
use tracing_subscriber::prelude::*;
use tracing_subscriber::{fmt, EnvFilter};
struct UserData {
id: u64,
// This field contains sensitive PII.
auth_token: String,
}
#[instrument(name = "process_user", skip(data.auth_token), fields(user.id = data.id))]
async fn process_user_data(data: UserData) {
// Simulate initial processing
tokio::time::sleep(std::time::Duration::from_millis(15)).await;
// Create and enter the span for the block below.
let db_span = span!(
Level::INFO,
"db_interaction",
target: "database",
db.system = "postgres",
db.statement = "UPDATE users SET last_seen = NOW()"
);
let _guard = db_span.enter();
{
tokio::time::sleep(std::time::Duration::from_millis(25)).await;
// This event is recorded within the context of the "db_interaction" span.
event!(Level::INFO, rows_affected = 1, "Database update successful");
}
}
#[tokio::main]
async fn main() {
const TARGET_NAME: &str = "user_service";
let filter_layer = EnvFilter::new(format!("{}=info", TARGET_NAME));
let fmt_layer = fmt::layer().json();
tracing_subscriber::registry()
.with(filter_layer)
.with(fmt_layer)
.init();
let user_data = UserData {
id: 42,
auth_token: "secret_jwt_token_string".to_string(),
};
process_user_data(user_data).await;
}