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