tower_http/trace/
on_request.rs

1use super::DEFAULT_MESSAGE_LEVEL;
2use http::Request;
3use tracing::Level;
4use tracing::Span;
5
6/// Trait used to tell [`Trace`] what to do when a request is received.
7///
8/// See the [module docs](../trace/index.html#on_request) for details on exactly when the
9/// `on_request` callback is called.
10///
11/// [`Trace`]: super::Trace
12pub trait OnRequest<B> {
13    /// Do the thing.
14    ///
15    /// `span` is the `tracing` [`Span`], corresponding to this request, produced by the closure
16    /// passed to [`TraceLayer::make_span_with`]. It can be used to [record field values][record]
17    /// that weren't known when the span was created.
18    ///
19    /// [`Span`]: https://docs.rs/tracing/latest/tracing/span/index.html
20    /// [record]: https://docs.rs/tracing/latest/tracing/span/struct.Span.html#method.record
21    /// [`TraceLayer::make_span_with`]: crate::trace::TraceLayer::make_span_with
22    fn on_request(&mut self, request: &Request<B>, span: &Span);
23}
24
25impl<B> OnRequest<B> for () {
26    #[inline]
27    fn on_request(&mut self, _: &Request<B>, _: &Span) {}
28}
29
30impl<B, F> OnRequest<B> for F
31where
32    F: FnMut(&Request<B>, &Span),
33{
34    fn on_request(&mut self, request: &Request<B>, span: &Span) {
35        self(request, span)
36    }
37}
38
39/// The default [`OnRequest`] implementation used by [`Trace`].
40///
41/// [`Trace`]: super::Trace
42#[derive(Clone, Debug)]
43pub struct DefaultOnRequest {
44    level: Level,
45}
46
47impl Default for DefaultOnRequest {
48    fn default() -> Self {
49        Self {
50            level: DEFAULT_MESSAGE_LEVEL,
51        }
52    }
53}
54
55impl DefaultOnRequest {
56    /// Create a new `DefaultOnRequest`.
57    pub fn new() -> Self {
58        Self::default()
59    }
60
61    /// Set the [`Level`] used for [tracing events].
62    ///
63    /// Please note that while this will set the level for the tracing events
64    /// themselves, it might cause them to lack expected information, like
65    /// request method or path. You can address this using
66    /// [`DefaultMakeSpan::level`].
67    ///
68    /// Defaults to [`Level::DEBUG`].
69    ///
70    /// [tracing events]: https://docs.rs/tracing/latest/tracing/#events
71    /// [`DefaultMakeSpan::level`]: crate::trace::DefaultMakeSpan::level
72    pub fn level(mut self, level: Level) -> Self {
73        self.level = level;
74        self
75    }
76}
77
78impl<B> OnRequest<B> for DefaultOnRequest {
79    fn on_request(&mut self, _: &Request<B>, _: &Span) {
80        event_dynamic_lvl!(self.level, "started processing request");
81    }
82}