blockscout_tracing_actix_web/
lib.rs

1//! `tracing-actix-web` provides [`TracingLogger`], a middleware to collect telemetry data from applications
2//! built on top of the [`actix-web`] framework.
3//!
4//! > `tracing-actix-web` was initially developed for the telemetry chapter of [Zero to Production In Rust](https://zero2prod.com), a hands-on introduction to backend development using the Rust programming language.
5//!
6//! # Getting started
7//!
8//! ## How to install
9//!
10//! Add `tracing-actix-web` to your dependencies:
11//!
12//! ```toml
13//! [dependencies]
14//! # ...
15//! tracing-actix-web = "0.7"
16//! tracing = "0.1"
17//! actix-web = "4"
18//! ```
19//!
20//! `tracing-actix-web` exposes three feature flags:
21//!
22//! - `opentelemetry_0_13`: attach [OpenTelemetry](https://github.com/open-telemetry/opentelemetry-rust)'s context to the root span using `opentelemetry` 0.13;
23//! - `opentelemetry_0_14`: same as above but using `opentelemetry` 0.14;
24//! - `opentelemetry_0_15`: same as above but using `opentelemetry` 0.15;
25//! - `opentelemetry_0_16`: same as above but using `opentelemetry` 0.16;
26//! - `opentelemetry_0_17`: same as above but using `opentelemetry` 0.17;
27//! - `opentelemetry_0_18`: same as above but using `opentelemetry` 0.18;
28//! - `opentelemetry_0_19`: same as above but using `opentelemetry` 0.19;
29//! - `opentelemetry_0_20`: same as above but using `opentelemetry` 0.20;
30//! - `opentelemetry_0_21`: same as above but using `opentelemetry` 0.21;
31//! - `emit_event_on_error`: emit a [`tracing`] event when request processing fails with an error (enabled by default).
32//! - `uuid_v7`: use the UUID v7 implementation inside [`RequestId`] instead of UUID v4 (disabled by default).
33//!
34//! ## Quickstart
35//!
36//! ```rust,compile_fail
37//! use actix_web::{App, web, HttpServer};
38//! use tracing_actix_web::TracingLogger;
39//!
40//! let server = HttpServer::new(|| {
41//!     App::new()
42//!         // Mount `TracingLogger` as a middleware
43//!         .wrap(TracingLogger::default())
44//!         .service( /*  */ )
45//! });
46//! ```
47//!
48//! Check out [the examples on GitHub](https://github.com/LukeMathWalker/tracing-actix-web/tree/main/examples) to get a taste of how [`TracingLogger`] can be used to observe and monitor your
49//! application.  
50//!
51//! # From zero to hero: a crash course in observability
52//!
53//! ## `tracing`: who art thou?
54//!
55//! [`TracingLogger`] is built on top of [`tracing`], a modern instrumentation framework with
56//! [a vibrant ecosystem](https://github.com/tokio-rs/tracing#related-crates).
57//!
58//! `tracing-actix-web`'s documentation provides a crash course in how to use [`tracing`] to instrument an `actix-web` application.  
59//! If you want to learn more check out ["Are we observable yet?"](https://www.lpalmieri.com/posts/2020-09-27-zero-to-production-4-are-we-observable-yet/) -
60//! it provides an in-depth introduction to the crate and the problems it solves within the bigger picture of [observability](https://docs.honeycomb.io/learning-about-observability/).
61//!
62//! ## The root span
63//!
64//! [`tracing::Span`] is the key abstraction in [`tracing`]: it represents a unit of work in your system.  
65//! A [`tracing::Span`] has a beginning and an end. It can include one or more **child spans** to represent sub-unit
66//! of works within a larger task.
67//!
68//! When your application receives a request, [`TracingLogger`] creates a new span - we call it the **[root span]**.  
69//! All the spans created _while_ processing the request will be children of the root span.
70//!
71//! [`tracing`] empowers us to attach structured properties to a span as a collection of key-value pairs.  
72//! Those properties can then be queried in a variety of tools (e.g. ElasticSearch, Honeycomb, DataDog) to
73//! understand what is happening in your system.  
74//!
75//! ## Customisation via [`RootSpanBuilder`]
76//!
77//! Troubleshooting becomes much easier when the root span has a _rich context_ - e.g. you can understand most of what
78//! happened when processing the request just by looking at the properties attached to the corresponding root span.  
79//!
80//! You might have heard of this technique as the [canonical log line pattern](https://stripe.com/blog/canonical-log-lines),
81//! popularised by Stripe. It is more recently discussed in terms of [high-cardinality events](https://www.honeycomb.io/blog/observability-a-manifesto/)
82//! by Honeycomb and other vendors in the observability space.
83//!
84//! [`TracingLogger`] gives you a chance to use the very same pattern: you can customise the properties attached
85//! to the root span in order to capture the context relevant to your specific domain.
86//!
87//! [`TracingLogger::default`] is equivalent to:
88//!
89//! ```rust
90//! use tracing_actix_web::{TracingLogger, DefaultRootSpanBuilder};
91//!
92//! // Two ways to initialise TracingLogger with the default root span builder
93//! let default = TracingLogger::default();
94//! let another_way = TracingLogger::<DefaultRootSpanBuilder>::new();
95//! ```
96//!
97//! We are delegating the construction of the root span to [`DefaultRootSpanBuilder`].  
98//! [`DefaultRootSpanBuilder`] captures, out of the box, several dimensions that are usually relevant when looking at an HTTP
99//! API: method, version, route, etc. - check out its documentation for an extensive list.
100//!
101//! You can customise the root span by providing your own implementation of the [`RootSpanBuilder`] trait.  
102//! Let's imagine, for example, that our system cares about a client identifier embedded inside an authorization header.
103//! We could add a `client_id` property to the root span using a custom builder, `DomainRootSpanBuilder`:
104//!
105//! ```rust
106//! use actix_web::body::MessageBody;
107//! use actix_web::dev::{ServiceResponse, ServiceRequest};
108//! use actix_web::Error;
109//! use tracing_actix_web::{TracingLogger, DefaultRootSpanBuilder, RootSpanBuilder};
110//! use tracing::Span;
111//!
112//! pub struct DomainRootSpanBuilder;
113//!
114//! impl RootSpanBuilder for DomainRootSpanBuilder {
115//!     fn on_request_start(request: &ServiceRequest) -> Span {
116//!         let client_id: &str = todo!("Somehow extract it from the authorization header");
117//!         tracing::info_span!("Request", client_id)
118//!     }
119//!
120//!     fn on_request_end<B: MessageBody>(_span: Span, _outcome: &Result<ServiceResponse<B>, Error>) {}
121//! }
122//!
123//! let custom_middleware = TracingLogger::<DomainRootSpanBuilder>::new();
124//! ```
125//!
126//! There is an issue, though: `client_id` is the _only_ property we are capturing.  
127//! With `DomainRootSpanBuilder`, as it is, we do not get any of that useful HTTP-related information provided by
128//! [`DefaultRootSpanBuilder`].  
129//!
130//! We can do better!
131//!
132//! ```rust
133//! use actix_web::body::MessageBody;
134//! use actix_web::dev::{ServiceResponse, ServiceRequest};
135//! use actix_web::Error;
136//! use tracing_actix_web::{TracingLogger, DefaultRootSpanBuilder, RootSpanBuilder};
137//! use tracing::Span;
138//!
139//! pub struct DomainRootSpanBuilder;
140//!
141//! impl RootSpanBuilder for DomainRootSpanBuilder {
142//!     fn on_request_start(request: &ServiceRequest) -> Span {
143//!         let client_id: &str = todo!("Somehow extract it from the authorization header");
144//!         tracing_actix_web::root_span!(request, client_id)
145//!     }
146//!
147//!     fn on_request_end<B: MessageBody>(span: Span, outcome: &Result<ServiceResponse<B>, Error>) {
148//!         DefaultRootSpanBuilder::on_request_end(span, outcome);
149//!     }
150//! }
151//!
152//! let custom_middleware = TracingLogger::<DomainRootSpanBuilder>::new();
153//! ```
154//!
155//! [`root_span!`] is a macro provided by `tracing-actix-web`: it creates a new span by combining all the HTTP properties tracked
156//! by [`DefaultRootSpanBuilder`] with the custom ones you specify when calling it (e.g. `client_id` in our example).  
157//!
158//! We need to use a macro because `tracing` requires all the properties attached to a span to be declared upfront, when the span is created.  
159//! You cannot add new ones afterwards. This makes it extremely fast, but it pushes us to reach for macros when we need some level of
160//! composition.
161//!
162//! [`root_span!`] exposes more or less the same knob you can find on `tracing`'s `span!` macro. You can, for example, customise
163//! the span level:
164//!
165//! ```rust
166//! use actix_web::body::MessageBody;
167//! use actix_web::dev::{ServiceResponse, ServiceRequest};
168//! use actix_web::Error;
169//! use tracing_actix_web::{TracingLogger, DefaultRootSpanBuilder, RootSpanBuilder, Level};
170//! use tracing::Span;
171//!
172//! pub struct CustomLevelRootSpanBuilder;
173//!
174//! impl RootSpanBuilder for CustomLevelRootSpanBuilder {
175//!     fn on_request_start(request: &ServiceRequest) -> Span {
176//!         let level = if request.path() == "/health_check" {
177//!             Level::DEBUG
178//!         } else {
179//!             Level::INFO
180//!         };
181//!         tracing_actix_web::root_span!(level = level, request)
182//!     }
183//!
184//!     fn on_request_end<B: MessageBody>(span: Span, outcome: &Result<ServiceResponse<B>, Error>) {
185//!         DefaultRootSpanBuilder::on_request_end(span, outcome);
186//!     }
187//! }
188//!
189//! let custom_middleware = TracingLogger::<CustomLevelRootSpanBuilder>::new();
190//! ```
191//!
192//! ## The [`RootSpan`] extractor
193//!
194//! It often happens that not all information about a task is known upfront, encoded in the incoming request.  
195//! You can use the [`RootSpan`] extractor to grab the root span in your handlers and attach more information
196//! to your root span as it becomes available:
197//!
198//! ```rust
199//! use actix_web::body::MessageBody;
200//! use actix_web::dev::{ServiceResponse, ServiceRequest};
201//! use actix_web::{Error, HttpResponse};
202//! use tracing_actix_web::{RootSpan, DefaultRootSpanBuilder, RootSpanBuilder};
203//! use tracing::Span;
204//! use actix_web::get;
205//! use tracing_actix_web::RequestId;
206//! use uuid::Uuid;
207//!
208//! #[get("/")]
209//! async fn handler(root_span: RootSpan) -> HttpResponse {
210//!     let application_id: &str = todo!("Some domain logic");
211//!     // Record the property value against the root span
212//!     root_span.record("application_id", &application_id);
213//!
214//!     // [...]
215//!     # todo!()
216//! }
217//!
218//! pub struct DomainRootSpanBuilder;
219//!
220//! impl RootSpanBuilder for DomainRootSpanBuilder {
221//!     fn on_request_start(request: &ServiceRequest) -> Span {
222//!         let client_id: &str = todo!("Somehow extract it from the authorization header");
223//!         // All fields you want to capture must be declared upfront.
224//!         // If you don't know the value (yet), use tracing's `Empty`
225//!         tracing_actix_web::root_span!(
226//!             request,
227//!             client_id, application_id = tracing::field::Empty
228//!         )
229//!     }
230//!
231//!     fn on_request_end<B: MessageBody>(span: Span, response: &Result<ServiceResponse<B>, Error>) {
232//!         DefaultRootSpanBuilder::on_request_end(span, response);
233//!     }
234//! }
235//! ```
236//!
237//! # Unique identifiers
238//!
239//! ## Request Id
240//!
241//! `tracing-actix-web` generates a unique identifier for each incoming request, the **request id**.
242//!
243//! You can extract the request id using the [`RequestId`] extractor:
244//!
245//! ```rust
246//! use actix_web::get;
247//! use tracing_actix_web::RequestId;
248//! use uuid::Uuid;
249//!
250//! #[get("/")]
251//! async fn index(request_id: RequestId) -> String {
252//!     format!("{}", request_id)
253//! }
254//! ```
255//!
256//! The request id is meant to identify all operations related to a particular request **within the boundary of your API**.
257//! If you need to **trace** a request across multiple services (e.g. in a microservice architecture), you want to look at the `trace_id` field - see the next section on OpenTelemetry for more details.
258//!
259//! Optionally, using the `uuid_v7` feature flag will allow [`RequestId`] to use UUID v7 instead of the currently used UUID v4.
260//!
261//! However, the [`uuid`] crate requires a compile time flag `uuid_unstable` to be passed in `RUSTFLAGS="--cfg uuid_unstable"` in order to compile. You can read more about it [here](https://docs.rs/uuid/latest/uuid/#unstable-features).
262//!
263//! ## Trace Id
264//!
265//! To fulfill a request you often have to perform additional I/O operations - e.g. calls to other REST or gRPC APIs, database queries, etc.
266//! **Distributed tracing** is the standard approach to **trace** a single request across the entirety of your stack.
267//!
268//! `tracing-actix-web` provides support for distributed tracing by supporting the [OpenTelemetry standard](https://opentelemetry.io/).  
269//! `tracing-actix-web` follows [OpenTelemetry's semantic convention](https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/overview.md#spancontext)
270//! for field names.
271//! Furthermore, it provides an `opentelemetry_0_17` feature flag to automatically performs trace propagation: it tries to extract the OpenTelemetry context out of the headers of incoming requests and, when it finds one, it sets it as the remote context for the current root span. The context is then propagated to your downstream dependencies if your HTTP or gRPC clients are OpenTelemetry-aware - e.g. using [`reqwest-middleware` and `reqwest-tracing`](https://github.com/TrueLayer/reqwest-middleware) if you are using `reqwest` as your HTTP client.  
272//! You can then find all logs for the same request across all the services it touched by looking for the `trace_id`, automatically logged by `tracing-actix-web`.
273//!
274//! If you add [`tracing-opentelemetry::OpenTelemetryLayer`](https://docs.rs/tracing-opentelemetry/0.17.0/tracing_opentelemetry/struct.OpenTelemetryLayer.html)
275//! in your `tracing::Subscriber` you will be able to export the root span (and all its children) as OpenTelemetry spans.
276//!
277//! Check out the [relevant example in the GitHub repository](https://github.com/LukeMathWalker/tracing-actix-web/tree/main/examples/opentelemetry) for reference.
278//!
279//! [root span]: crate::RootSpan
280//! [`actix-web`]: https://docs.rs/actix-web/4.0.0-beta.13/actix_web/index.html
281mod middleware;
282mod request_id;
283mod root_span;
284mod root_span_builder;
285
286pub use middleware::{SkipHttpTrace, StreamSpan, TracingLogger};
287pub use request_id::RequestId;
288pub use root_span::RootSpan;
289pub use root_span_builder::{DefaultRootSpanBuilder, RootSpanBuilder};
290// Re-exporting the `Level` enum since it's used in our `root_span!` macro
291pub use tracing::Level;
292
293#[doc(hidden)]
294pub mod root_span_macro;
295
296mutually_exclusive_features::none_or_one_of!(
297    "opentelemetry_0_13",
298    "opentelemetry_0_14",
299    "opentelemetry_0_15",
300    "opentelemetry_0_16",
301    "opentelemetry_0_17",
302    "opentelemetry_0_18",
303    "opentelemetry_0_19",
304    "opentelemetry_0_20",
305    "opentelemetry_0_21",
306);
307
308#[cfg(any(
309    feature = "opentelemetry_0_13",
310    feature = "opentelemetry_0_14",
311    feature = "opentelemetry_0_15",
312    feature = "opentelemetry_0_16",
313    feature = "opentelemetry_0_17",
314    feature = "opentelemetry_0_18",
315    feature = "opentelemetry_0_19",
316    feature = "opentelemetry_0_20",
317    feature = "opentelemetry_0_21",
318))]
319mod otel;