Macro tracing_actix_web::root_span[][src]

macro_rules! root_span {
    ($request:ident) => { ... };
    ($request:ident, $($field:tt)*) => { ... };
}

root_span! creates a new tracing::Span. It empowers you to add custom properties to the root span on top of the HTTP properties tracked by DefaultRootSpanBuilder.

Why a macro?

tracing requires all the properties attached to a span to be declared upfront, when the span is created. 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 composition.

Macro syntax

The first argument passed to root_span! must be a reference to an actix_web::dev::ServiceRequest.

use actix_web::dev::{ServiceResponse, ServiceRequest};
use actix_web::Error;
use tracing_actix_web::{TracingLogger, DefaultRootSpanBuilder, RootSpanBuilder, root_span};
use tracing::Span;

pub struct CustomRootSpanBuilder;

impl RootSpanBuilder for CustomRootSpanBuilder {
    fn on_request_start(request: &ServiceRequest) -> Span {
        root_span!(request)
    }

    fn on_request_end<B>(span: Span, outcome: &Result<ServiceResponse<B>, Error>) {
        DefaultRootSpanBuilder::on_request_end(span, outcome);
    }
}

If nothing else is specified, the span generated by root_span! is identical to the one you’d get by using DefaultRootSpanBuilder.

You can define new fields following the same syntax of tracing::info_span! for fields:


// Define a `client_id` field as empty. It might be populated later.
tracing_actix_web::root_span!(request, client_id = tracing::field::Empty);

// Define a `name` field with a known value, `AppName`.
tracing_actix_web::root_span!(request, name = "AppName");

// Define an `app_id` field using the variable with the same name as value.
let app_id = "XYZ";
tracing_actix_web::root_span!(request, app_id);

// All together
tracing_actix_web::root_span!(request, client_id = tracing::field::Empty, name = "AppName", app_id);