Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat!: record unique request_id for every request #17

Merged
merged 6 commits into from
Oct 23, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -14,15 +14,20 @@ edition = "2021"
rust-version = "1.63"
exclude = ["*.png"]

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[features]
default = ["request_id"]
# Record unique `request_id` for every request
request_id = ["dep:uuid"]

[dependencies]
tide = { version = "0.16", default-features = false }
tracing = "0.1"
tracing-futures = "0.2"
async-trait = "0.1"
uuid = { version = "1.4.1", features = ["v4"], optional = true}

[dev-dependencies]
tide = { version = "0.16", default-features = false, features = ["h1-server"] }
async-std = { version = "1.9", features = ["attributes"] }
tracing-subscriber = "0.3"

17 changes: 16 additions & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ use std::time::Instant;
use tide::{Middleware, Next, Request};
use tracing::{error, error_span, field, info, info_span, warn, warn_span};
use tracing_futures::Instrument;
#[cfg(feature = "request_id")]
use uuid::Uuid;

/// Log all incoming requests and responses with tracing spans.
///
Expand Down Expand Up @@ -57,7 +59,20 @@ impl TraceMiddleware {
});
response
}
.instrument(info_span!("Request", http.method = %method, http.target = %path))
.instrument({
let span = info_span!(
"Request",
http.method = %method,
http.target = %path,
request_id = field::Empty,
);

// If the request_id feature is enabled, add a new request_id record to the span.
#[cfg(feature = "request_id")]
span.record("request_id", Uuid::new_v4().to_string());

span
})
.await)
}
}
Expand Down