Debian Codegraph @

third_party/rust/warp/examples/tracing.rs

raw
1 //! [`tracing`] is a framework for instrumenting Rust programs to
2 //! collect scoped, structured, and async-aware diagnostics. This example
3 //! demonstrates how the `warp::trace` module can be used to instrument `warp`
4 //! applications with `tracing`.
5 //!
6 //! [`tracing`]: https://crates.io/crates/tracing
7 #![deny(warnings)]
8 use tracing_subscriber::fmt::format::FmtSpan;
9 use warp::Filter;
10
11 #[tokio::main]
12 async fn main() {
13 // Filter traces based on the RUST_LOG env var, or, if it's not set,
14 // default to show the output of the example.
15 let filter = std::env::var("RUST_LOG").unwrap_or_else(|_| "tracing=info,warp=debug".to_owned());
16
17 // Configure the default `tracing` subscriber.
18 // The `fmt` subscriber from the `tracing-subscriber` crate logs `tracing`
19 // events to stdout. Other subscribers are available for integrating with
20 // distributed tracing systems such as OpenTelemetry.
21 tracing_subscriber::fmt()
22 // Use the filter we built above to determine which traces to record.
23 .with_env_filter(filter)
24 // Record an event when each span closes. This can be used to time our
25 // routes' durations!
26 .with_span_events(FmtSpan::CLOSE)
27 .init();
28
29 let hello = warp::path("hello")
30 .and(warp::get())
31 // When the `hello` route is called, emit a `tracing` event.
32 .map(|| {
33 tracing::info!("saying hello...");
34 "Hello, World!"
35 })
36 // Wrap the route in a `tracing` span to add the route's name as context
37 // to any events that occur inside it.
38 .with(warp::trace::named("hello"));
39
40 let goodbye = warp::path("goodbye")
41 .and(warp::get())
42 .map(|| {
43 tracing::info!("saying goodbye...");
44 "So long and thanks for all the fish!"
45 })
46 // We can also provide our own custom `tracing` spans to wrap a route.
47 .with(warp::trace(|info| {
48 // Construct our own custom span for this route.
49 tracing::info_span!("goodbye", req.path = ?info.path())
50 }));
51
52 let routes = hello
53 .or(goodbye)
54 // Wrap all the routes with a filter that creates a `tracing` span for
55 // each request we receive, including data about the request.
56 .with(warp::trace::request());
57
58 warp::serve(routes).run(([127, 0, 0, 1], 3030)).await;
59 }