Tracing Subscriber Env Filter Init
Bootstrap tracing with EnvFilter directives, JSON output in production, pretty console in development, and span lifecycle events.
Code
use tracing::{debug, error, info, instrument, warn};
use tracing_subscriber::{fmt, layer::SubscriberExt, util::SubscriberInitExt, EnvFilter};
#[instrument(name = "order_flow", skip(payload))]
fn process_order(order_id: u64, payload: &str) -> u64 {
debug!(bytes = payload.len(), "payload received");
let total = payload.len() as u64 * order_id % 97;
info!(total, "order total computed");
total
}
fn init_tracing() {
let filter = EnvFilter::try_from_default_env()
.unwrap_or_else(|_| EnvFilter::new("info,order_service=debug"));
let is_prod = std::env::var("APP_ENV")
.map(|v| v == "production")
.unwrap_or(false);
let registry = tracing_subscriber::registry().with(filter);
if is_prod {
registry
.with(fmt::layer().json().flatten_event(true))
.init();
} else {
registry
.with(fmt::layer().pretty().with_target(false))
.init();
}
}
fn main() {
init_tracing();
let span = tracing::info_span!("startup", version = env!("CARGO_PKG_VERSION"));
let _guard = span.enter();
info!("service starting");
warn!("cache warmup skipped");
let total = process_order(42, "line-item;quantity=3");
error!(total, "downstream settlement slow");
drop(_guard);
info!("shutdown complete");
}How it works
Count the functions process_order, init_tracing and main as the entire surface area of Tracing Subscriber Env Filter Init.
Points of care
- Plan for an install step:
tracing::andtracing_subscriber::are a real dependency, resolved by the package manager.
Putting it to use
Signature: fn process_order(order_id: u64, payload: &str) -> u64
Running the file executes main, which drives init_tracing and process_order in order.
Core lines
.unwrap_or_else(|_| EnvFilter::new("info,order_service=debug"));
fn process_order(order_id: u64, payload: &str) -> u64 {
debug!(bytes = payload.len(), "payload received");
let total = payload.len() as u64 * order_id % 97;
info!(total, "order total computed");
total
}
.unwrap_or(false);
Interactive Tools for This Topic
Dotenv File ParserParse .env file content into a JSON object, handling comments, export prefixes, single quotes, and double-quoted escape sequences.HTTP Retry & Backoff CalculatorSimulate exponential backoff retry schedules with Full, Equal, Decorrelated, or No Jitter to inspect per-attempt wait times and cumulative latency.
FAQ
- Does this require external packages?
- Yes — `tracing::` and `tracing_subscriber::`. Add them to your project before running the snippet.
Report a problem with this exampleOpens a pre-filled issue on GitHub.