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