Skip to content

Commit

Permalink
Make log level used for trace spans configurable
Browse files Browse the repository at this point in the history
This is a minimally invasive fix for tower-rs#123. It's certainly not ideal,
API-wise, but at least it allows users to add request information to
their logs without having to set the log level to DEBUG.

Close tower-rs#123
  • Loading branch information
hannobraun committed Aug 19, 2021
1 parent a5d32d1 commit 015027f
Showing 1 changed file with 57 additions and 16 deletions.
73 changes: 57 additions & 16 deletions tower-http/src/trace/make_span.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
use http::Request;
use tracing::Span;
use tracing::{Level, Span};

use super::DEFAULT_MESSAGE_LEVEL;

/// Trait used to generate [`Span`]s from requests. [`Trace`] wraps all request handling in this
/// span.
Expand Down Expand Up @@ -32,17 +34,29 @@ where
/// [`Trace`]: super::Trace
#[derive(Debug, Clone)]
pub struct DefaultMakeSpan {
level: Level,
include_headers: bool,
}

impl DefaultMakeSpan {
/// Create a new `DefaultMakeSpan`.
pub fn new() -> Self {
Self {
level: DEFAULT_MESSAGE_LEVEL,
include_headers: false,
}
}

/// Set the [`Level`] used for the [tracing span].
///
/// Defaults to [`Level::DEBUG`].
///
/// [tracing span]: https://docs.rs/tracing/latest/tracing/#spans
pub fn level(mut self, level: Level) -> Self {
self.level = level;
self
}

/// Include request headers on the [`Span`].
///
/// By default headers are not included.
Expand All @@ -62,21 +76,48 @@ impl Default for DefaultMakeSpan {

impl<B> MakeSpan<B> for DefaultMakeSpan {
fn make_span(&mut self, request: &Request<B>) -> Span {
if self.include_headers {
tracing::debug_span!(
"request",
method = %request.method(),
uri = %request.uri(),
version = ?request.version(),
headers = ?request.headers(),
)
} else {
tracing::debug_span!(
"request",
method = %request.method(),
uri = %request.uri(),
version = ?request.version(),
)
// This ugly macro is needed, unfortunately, because `tracing::span!`
// required the level argument to be static. Meaning we can't just pass
// `self.level`.
macro_rules! make_span {
($level:expr) => {
if self.include_headers {
tracing::span!(
$level,
"request",
method = %request.method(),
uri = %request.uri(),
version = ?request.version(),
headers = ?request.headers(),
)
} else {
tracing::span!(
$level,
"request",
method = %request.method(),
uri = %request.uri(),
version = ?request.version(),
)
}
}
}

match self.level {
Level::ERROR => {
make_span!(Level::ERROR)
}
Level::WARN => {
make_span!(Level::WARN)
}
Level::INFO => {
make_span!(Level::INFO)
}
Level::DEBUG => {
make_span!(Level::DEBUG)
}
Level::TRACE => {
make_span!(Level::TRACE)
}
}
}
}

0 comments on commit 015027f

Please sign in to comment.