Skip to main content

actix_web/middleware/
logger.rs

1//! For middleware documentation, see [`Logger`].
2
3use std::{
4    borrow::Cow,
5    collections::HashSet,
6    env,
7    fmt::{self, Display as _},
8    future::Future,
9    marker::PhantomData,
10    pin::Pin,
11    rc::Rc,
12    task::{Context, Poll},
13};
14
15use actix_service::{Service, Transform};
16#[expect(deprecated, reason = "preserve the public ready future type")]
17use actix_utils::future::{ready, Ready};
18use bytes::Bytes;
19use futures_core::ready;
20use log::{debug, warn, Level};
21use pin_project_lite::pin_project;
22#[cfg(feature = "unicode")]
23use regex::Regex;
24#[cfg(not(feature = "unicode"))]
25use regex_lite::Regex;
26use time::{format_description::well_known::Rfc3339, OffsetDateTime};
27
28use crate::{
29    body::{BodySize, MessageBody},
30    http::header::HeaderName,
31    service::{ServiceRequest, ServiceResponse},
32    Error, Result,
33};
34
35/// Middleware for logging request and response summaries to the terminal.
36///
37/// This middleware uses the `log` crate to output information. Enable `log`'s output for the
38/// "actix_web" scope using [`env_logger`](https://docs.rs/env_logger) or similar crate.
39///
40/// # Default Format
41/// The [`default`](Logger::default) Logger uses the following format:
42///
43/// ```plain
44/// %a "%r" %s %b "%{Referer}i" "%{User-Agent}i" %T
45///
46/// Example Output:
47/// 127.0.0.1:54278 "GET /test HTTP/1.1" 404 20 "-" "HTTPie/2.2.0" 0.001074
48/// ```
49///
50/// # Examples
51/// ```
52/// use actix_web::{middleware::Logger, App};
53///
54/// // access logs are printed with the INFO level so ensure it is enabled by default
55/// env_logger::init_from_env(env_logger::Env::new().default_filter_or("info"));
56///
57/// let app = App::new()
58///     // .wrap(Logger::default())
59///     .wrap(Logger::new("%a %{User-Agent}i"));
60/// ```
61///
62/// # Format
63/// Variable | Description
64/// -------- | -----------
65/// `%%` | The percent sign
66/// `%a` | Peer IP address (or IP address of reverse proxy if used)
67/// `%t` | Time when the request started processing (in RFC 3339 format)
68/// `%r` | First line of request (Example: `GET /test HTTP/1.1`)
69/// `%s` | Response status code
70/// `%b` | Size of response in bytes, including HTTP headers
71/// `%T` | Time taken to serve the request, in seconds to 6 decimal places
72/// `%D` | Time taken to serve the request, in milliseconds
73/// `%U` | Request URL
74/// `%{r}a` | "Real IP" remote address **\***
75/// `%{FOO}i` | `request.headers["FOO"]`
76/// `%{FOO}o` | `response.headers["FOO"]`
77/// `%{FOO}e` | `env_var["FOO"]`
78/// `%{FOO}xi` | [Custom request replacement](Logger::custom_request_replace) labelled "FOO"
79/// `%{FOO}xo` | [Custom response replacement](Logger::custom_response_replace) labelled "FOO"
80///
81/// # Security
82/// **\*** "Real IP" remote address is calculated using
83/// [`ConnectionInfo::realip_remote_addr()`](crate::dev::ConnectionInfo::realip_remote_addr())
84///
85/// If you use this value, ensure that all requests come from trusted hosts. Otherwise, it is
86/// trivial for the remote client to falsify their source IP address.
87#[derive(Debug)]
88pub struct Logger(Rc<Inner>);
89
90#[derive(Debug, Clone)]
91struct Inner {
92    format: Format,
93    exclude: HashSet<String>,
94    exclude_regex: Vec<Regex>,
95    log_target: Cow<'static, str>,
96    log_level: Level,
97}
98
99impl Logger {
100    /// Create `Logger` middleware with the specified `format`.
101    pub fn new(format: &str) -> Logger {
102        Logger(Rc::new(Inner {
103            format: Format::new(format),
104            exclude: HashSet::new(),
105            exclude_regex: Vec::new(),
106            log_target: Cow::Borrowed(module_path!()),
107            log_level: Level::Info,
108        }))
109    }
110
111    /// Ignore and do not log access info for specified path.
112    pub fn exclude<T: Into<String>>(mut self, path: T) -> Self {
113        Rc::get_mut(&mut self.0)
114            .unwrap()
115            .exclude
116            .insert(path.into());
117        self
118    }
119
120    /// Ignore and do not log access info for paths that match regex.
121    pub fn exclude_regex<T: Into<String>>(mut self, path: T) -> Self {
122        let inner = Rc::get_mut(&mut self.0).unwrap();
123        inner.exclude_regex.push(Regex::new(&path.into()).unwrap());
124        self
125    }
126
127    /// Sets the logging target to `target`.
128    ///
129    /// By default, the log target is `module_path!()` of the log call location. In our case, that
130    /// would be `actix_web::middleware::logger`.
131    ///
132    /// # Examples
133    /// Using `.log_target("http_log")` would have this effect on request logs:
134    /// ```diff
135    /// - [2015-10-21T07:28:00Z INFO  actix_web::middleware::logger] 127.0.0.1 "GET / HTTP/1.1" 200 88 "-" "dmc/1.0" 0.001985
136    /// + [2015-10-21T07:28:00Z INFO  http_log] 127.0.0.1 "GET / HTTP/1.1" 200 88 "-" "dmc/1.0" 0.001985
137    ///                               ^^^^^^^^
138    /// ```
139    pub fn log_target(mut self, target: impl Into<Cow<'static, str>>) -> Self {
140        let inner = Rc::get_mut(&mut self.0).unwrap();
141        inner.log_target = target.into();
142        self
143    }
144
145    /// Sets the log level to `level`.
146    ///
147    /// By default, the log level is `Level::Info`.
148    ///
149    /// # Examples
150    /// Using `.log_level(Level::Debug)` would have this effect on request logs:
151    /// ```diff
152    /// - [2015-10-21T07:28:00Z INFO  actix_web::middleware::logger] 127.0.0.1 "GET / HTTP/1.1" 200 88 "-" "dmc/1.0" 0.001985
153    /// + [2015-10-21T07:28:00Z DEBUG  actix_web::middleware::logger] 127.0.0.1 "GET / HTTP/1.1" 200 88 "-" "dmc/1.0" 0.001985
154    ///                         ^^^^^^
155    /// ```
156    pub fn log_level(mut self, level: log::Level) -> Self {
157        let inner = Rc::get_mut(&mut self.0).unwrap();
158        inner.log_level = level;
159        self
160    }
161
162    /// Register a function that receives a ServiceRequest and returns a String for use in the
163    /// log line. The label passed as the first argument should match a replacement substring in
164    /// the logger format like `%{label}xi`.
165    ///
166    /// It is convention to print "-" to indicate no output instead of an empty string.
167    ///
168    /// # Examples
169    /// ```
170    /// # use actix_web::http::{header::HeaderValue};
171    /// # use actix_web::middleware::Logger;
172    /// # fn parse_jwt_id (_req: Option<&HeaderValue>) -> String { "jwt_uid".to_owned() }
173    /// Logger::new("example %{JWT_ID}xi")
174    ///     .custom_request_replace("JWT_ID", |req| parse_jwt_id(req.headers().get("Authorization")));
175    /// ```
176    pub fn custom_request_replace(
177        mut self,
178        label: &str,
179        f: impl Fn(&ServiceRequest) -> String + 'static,
180    ) -> Self {
181        let inner = Rc::get_mut(&mut self.0).unwrap();
182
183        let ft = inner.format.0.iter_mut().find(
184            |ft| matches!(ft, FormatText::CustomRequest(unit_label, _) if label == unit_label),
185        );
186
187        if let Some(FormatText::CustomRequest(_, request_fn)) = ft {
188            // replace into None or previously registered fn using same label
189            request_fn.replace(CustomRequestFn {
190                inner_fn: Rc::new(f),
191            });
192        } else {
193            // non-printed request replacement function diagnostic
194            debug!(
195                "Attempted to register custom request logging function for nonexistent label: {}",
196                label
197            );
198        }
199
200        self
201    }
202
203    /// Register a function that receives a `ServiceResponse` and returns a string for use in the
204    /// log line.
205    ///
206    /// The label passed as the first argument should match a replacement substring in
207    /// the logger format like `%{label}xo`.
208    ///
209    /// It is convention to print "-" to indicate no output instead of an empty string.
210    ///
211    /// The replacement function does not have access to the response body.
212    ///
213    /// # Examples
214    /// ```
215    /// # use actix_web::{dev::ServiceResponse, middleware::Logger};
216    /// fn log_if_error(res: &ServiceResponse) -> String {
217    ///     if res.status().as_u16() >= 400 {
218    ///         "ERROR".to_string()
219    ///     } else {
220    ///         "-".to_string()
221    ///     }
222    /// }
223    ///
224    /// Logger::new("example %{ERROR_STATUS}xo")
225    ///     .custom_response_replace("ERROR_STATUS", |res| log_if_error(res) );
226    /// ```
227    pub fn custom_response_replace(
228        mut self,
229        label: &str,
230        f: impl Fn(&ServiceResponse) -> String + 'static,
231    ) -> Self {
232        let inner = Rc::get_mut(&mut self.0).unwrap();
233
234        let ft = inner.format.0.iter_mut().find(
235            |ft| matches!(ft, FormatText::CustomResponse(unit_label, _) if label == unit_label),
236        );
237
238        if let Some(FormatText::CustomResponse(_, res_fn)) = ft {
239            *res_fn = Some(CustomResponseFn {
240                inner_fn: Rc::new(f),
241            });
242        } else {
243            debug!(
244                "Attempted to register custom response logging function for non-existent label: {}",
245                label
246            );
247        }
248
249        self
250    }
251}
252
253impl Default for Logger {
254    /// Create `Logger` middleware with format:
255    ///
256    /// ```plain
257    /// %a "%r" %s %b "%{Referer}i" "%{User-Agent}i" %T
258    /// ```
259    fn default() -> Logger {
260        Logger(Rc::new(Inner {
261            format: Format::default(),
262            exclude: HashSet::new(),
263            exclude_regex: Vec::new(),
264            log_target: Cow::Borrowed(module_path!()),
265            log_level: Level::Info,
266        }))
267    }
268}
269
270#[expect(deprecated, reason = "preserve the public ready future type")]
271impl<S, B> Transform<S, ServiceRequest> for Logger
272where
273    S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error>,
274    B: MessageBody,
275{
276    type Response = ServiceResponse<StreamLog<B>>;
277    type Error = Error;
278    type Transform = LoggerMiddleware<S>;
279    type InitError = ();
280    type Future = Ready<Result<Self::Transform, Self::InitError>>;
281
282    fn new_transform(&self, service: S) -> Self::Future {
283        for unit in &self.0.format.0 {
284            if let FormatText::CustomRequest(label, None) = unit {
285                warn!(
286                    "No custom request replacement function was registered for label: {}",
287                    label
288                );
289            }
290
291            if let FormatText::CustomResponse(label, None) = unit {
292                warn!(
293                    "No custom response replacement function was registered for label: {}",
294                    label
295                );
296            }
297        }
298
299        ready(Ok(LoggerMiddleware {
300            service,
301            inner: Rc::clone(&self.0),
302        }))
303    }
304}
305
306/// Logger middleware service.
307pub struct LoggerMiddleware<S> {
308    inner: Rc<Inner>,
309    service: S,
310}
311
312impl<S, B> Service<ServiceRequest> for LoggerMiddleware<S>
313where
314    S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error>,
315    B: MessageBody,
316{
317    type Response = ServiceResponse<StreamLog<B>>;
318    type Error = Error;
319    type Future = LoggerResponse<S, B>;
320
321    actix_service::forward_ready!(service);
322
323    fn call(&self, req: ServiceRequest) -> Self::Future {
324        let excluded = self.inner.exclude.contains(req.path())
325            || self
326                .inner
327                .exclude_regex
328                .iter()
329                .any(|r| r.is_match(req.path()));
330
331        if excluded {
332            LoggerResponse {
333                fut: self.service.call(req),
334                format: None,
335                time: OffsetDateTime::now_utc(),
336                log_target: Cow::Borrowed(""),
337                log_level: self.inner.log_level,
338                _phantom: PhantomData,
339            }
340        } else {
341            let now = OffsetDateTime::now_utc();
342            let mut format = self.inner.format.clone();
343
344            for unit in &mut format.0 {
345                unit.render_request(now, &req);
346            }
347
348            LoggerResponse {
349                fut: self.service.call(req),
350                format: Some(format),
351                time: now,
352                log_target: self.inner.log_target.clone(),
353                log_level: self.inner.log_level,
354                _phantom: PhantomData,
355            }
356        }
357    }
358}
359
360pin_project! {
361    pub struct LoggerResponse<S, B>
362    where
363        B: MessageBody,
364        S: Service<ServiceRequest>,
365    {
366        #[pin]
367        fut: S::Future,
368        time: OffsetDateTime,
369        format: Option<Format>,
370        log_target: Cow<'static, str>,
371        log_level: Level,
372        _phantom: PhantomData<B>,
373    }
374}
375
376impl<S, B> Future for LoggerResponse<S, B>
377where
378    B: MessageBody,
379    S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error>,
380{
381    type Output = Result<ServiceResponse<StreamLog<B>>, Error>;
382
383    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
384        let this = self.project();
385
386        let res = match ready!(this.fut.poll(cx)) {
387            Ok(res) => res,
388            Err(err) => return Poll::Ready(Err(err)),
389        };
390
391        if let Some(error) = res.response().error() {
392            debug!("Error in response: {:?}", error);
393        }
394
395        let res = if let Some(ref mut format) = this.format {
396            // to avoid polluting all the Logger types with the body parameter we swap the body
397            // out temporarily since it's not usable in custom response functions anyway
398
399            let (req, res) = res.into_parts();
400            let (res, body) = res.into_parts();
401
402            let temp_res = ServiceResponse::new(req, res.map_into_boxed_body());
403
404            for unit in &mut format.0 {
405                unit.render_response(&temp_res);
406            }
407
408            // re-construct original service response
409            let (req, res) = temp_res.into_parts();
410            ServiceResponse::new(req, res.set_body(body))
411        } else {
412            res
413        };
414
415        let time = *this.time;
416        let format = this.format.take();
417        let log_target = this.log_target.clone();
418        let log_level = *this.log_level;
419
420        Poll::Ready(Ok(res.map_body(move |_, body| StreamLog {
421            body,
422            time,
423            format,
424            size: 0,
425            log_target,
426            log_level,
427        })))
428    }
429}
430
431pin_project! {
432    pub struct StreamLog<B> {
433        #[pin]
434        body: B,
435        format: Option<Format>,
436        size: usize,
437        time: OffsetDateTime,
438        log_target: Cow<'static, str>,
439        log_level: Level
440    }
441
442    impl<B> PinnedDrop for StreamLog<B> {
443        fn drop(this: Pin<&mut Self>) {
444            if let Some(ref format) = this.format {
445                let render = |fmt: &mut fmt::Formatter<'_>| {
446                    for unit in &format.0 {
447                        unit.render(fmt, this.size, this.time)?;
448                    }
449                    Ok(())
450                };
451
452                log::log!(
453                    target: this.log_target.as_ref(),
454                    this.log_level,
455                    "{}", FormatDisplay(&render)
456                );
457            }
458        }
459    }
460}
461
462impl<B: MessageBody> MessageBody for StreamLog<B> {
463    type Error = B::Error;
464
465    #[inline]
466    fn size(&self) -> BodySize {
467        self.body.size()
468    }
469
470    fn poll_next(
471        self: Pin<&mut Self>,
472        cx: &mut Context<'_>,
473    ) -> Poll<Option<Result<Bytes, Self::Error>>> {
474        let this = self.project();
475
476        match ready!(this.body.poll_next(cx)) {
477            Some(Ok(chunk)) => {
478                *this.size += chunk.len();
479                Poll::Ready(Some(Ok(chunk)))
480            }
481            Some(Err(err)) => Poll::Ready(Some(Err(err))),
482            None => Poll::Ready(None),
483        }
484    }
485}
486
487/// A formatting style for the `Logger` consisting of multiple concatenated `FormatText` items.
488#[derive(Debug, Clone)]
489struct Format(Vec<FormatText>);
490
491impl Default for Format {
492    /// Return the default formatting style for the `Logger`:
493    fn default() -> Format {
494        Format::new(r#"%a "%r" %s %b "%{Referer}i" "%{User-Agent}i" %T"#)
495    }
496}
497
498impl Format {
499    /// Create a `Format` from a format string.
500    ///
501    /// Returns `None` if the format string syntax is incorrect.
502    pub fn new(s: &str) -> Format {
503        log::trace!("Access log format: {}", s);
504        let fmt = Regex::new(r"%(\{([A-Za-z0-9\-_]+)\}([aioe]|x[io])|[%atPrUsbTD]?)").unwrap();
505
506        let mut idx = 0;
507        let mut results = Vec::new();
508        for cap in fmt.captures_iter(s) {
509            let m = cap.get(0).unwrap();
510            let pos = m.start();
511            if idx != pos {
512                results.push(FormatText::Str(s[idx..pos].to_owned()));
513            }
514            idx = m.end();
515
516            if let Some(key) = cap.get(2) {
517                results.push(match cap.get(3).unwrap().as_str() {
518                    "a" if key.as_str() == "r" => FormatText::RealIpRemoteAddr,
519                    // only `%{r}a` is supported; keep other `%{..}a` sequences as literal text
520                    "a" => FormatText::Str(m.as_str().to_owned()),
521                    "i" => FormatText::RequestHeader(HeaderName::try_from(key.as_str()).unwrap()),
522                    "o" => FormatText::ResponseHeader(HeaderName::try_from(key.as_str()).unwrap()),
523                    "e" => FormatText::EnvironHeader(key.as_str().to_owned()),
524                    "xi" => FormatText::CustomRequest(key.as_str().to_owned(), None),
525                    "xo" => FormatText::CustomResponse(key.as_str().to_owned(), None),
526                    _ => unreachable!(),
527                })
528            } else {
529                let m = cap.get(1).unwrap();
530                results.push(match m.as_str() {
531                    "%" => FormatText::Percent,
532                    "a" => FormatText::RemoteAddr,
533                    "t" => FormatText::RequestTime,
534                    "r" => FormatText::RequestLine,
535                    "s" => FormatText::ResponseStatus,
536                    "b" => FormatText::ResponseSize,
537                    "U" => FormatText::UrlPath,
538                    "T" => FormatText::Time,
539                    "D" => FormatText::TimeMillis,
540                    _ => FormatText::Str(m.as_str().to_owned()),
541                });
542            }
543        }
544        if idx != s.len() {
545            results.push(FormatText::Str(s[idx..].to_owned()));
546        }
547
548        Format(results)
549    }
550}
551
552/// A string of text to be logged.
553///
554/// This is either one of the data fields supported by the `Logger`, or a custom `String`.
555#[non_exhaustive]
556#[derive(Debug, Clone)]
557enum FormatText {
558    Str(String),
559    Percent,
560    RequestLine,
561    RequestTime,
562    ResponseStatus,
563    ResponseSize,
564    Time,
565    TimeMillis,
566    RemoteAddr,
567    RealIpRemoteAddr,
568    UrlPath,
569    RequestHeader(HeaderName),
570    ResponseHeader(HeaderName),
571    EnvironHeader(String),
572    CustomRequest(String, Option<CustomRequestFn>),
573    CustomResponse(String, Option<CustomResponseFn>),
574}
575
576#[derive(Clone)]
577struct CustomRequestFn {
578    inner_fn: Rc<dyn Fn(&ServiceRequest) -> String>,
579}
580
581impl CustomRequestFn {
582    fn call(&self, req: &ServiceRequest) -> String {
583        (self.inner_fn)(req)
584    }
585}
586
587impl fmt::Debug for CustomRequestFn {
588    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
589        f.write_str("custom_request_fn")
590    }
591}
592
593#[derive(Clone)]
594struct CustomResponseFn {
595    inner_fn: Rc<dyn Fn(&ServiceResponse) -> String>,
596}
597
598impl CustomResponseFn {
599    fn call(&self, res: &ServiceResponse) -> String {
600        (self.inner_fn)(res)
601    }
602}
603
604impl fmt::Debug for CustomResponseFn {
605    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
606        f.write_str("custom_response_fn")
607    }
608}
609
610impl FormatText {
611    fn render(
612        &self,
613        fmt: &mut fmt::Formatter<'_>,
614        size: usize,
615        entry_time: OffsetDateTime,
616    ) -> Result<(), fmt::Error> {
617        match self {
618            FormatText::Str(ref string) => fmt.write_str(string),
619            FormatText::Percent => "%".fmt(fmt),
620            FormatText::ResponseSize => size.fmt(fmt),
621            FormatText::Time => {
622                let rt = OffsetDateTime::now_utc() - entry_time;
623                let rt = rt.as_seconds_f64();
624                fmt.write_fmt(format_args!("{:.6}", rt))
625            }
626            FormatText::TimeMillis => {
627                let rt = OffsetDateTime::now_utc() - entry_time;
628                let rt = (rt.whole_nanoseconds() as f64) / 1_000_000.0;
629                fmt.write_fmt(format_args!("{:.6}", rt))
630            }
631            FormatText::EnvironHeader(ref name) => {
632                if let Ok(val) = env::var(name) {
633                    fmt.write_fmt(format_args!("{}", val))
634                } else {
635                    "-".fmt(fmt)
636                }
637            }
638            _ => Ok(()),
639        }
640    }
641
642    fn render_response(&mut self, res: &ServiceResponse) {
643        match self {
644            FormatText::ResponseStatus => {
645                *self = FormatText::Str(format!("{}", res.status().as_u16()))
646            }
647
648            FormatText::ResponseHeader(ref name) => {
649                let s = if let Some(val) = res.headers().get(name) {
650                    String::from_utf8_lossy(val.as_bytes()).into_owned()
651                } else {
652                    "-".to_owned()
653                };
654                *self = FormatText::Str(s.to_string())
655            }
656
657            FormatText::CustomResponse(_, res_fn) => {
658                let text = match res_fn {
659                    Some(res_fn) => FormatText::Str(res_fn.call(res)),
660                    None => FormatText::Str("-".to_owned()),
661                };
662
663                *self = text;
664            }
665
666            _ => {}
667        }
668    }
669
670    fn render_request(&mut self, now: OffsetDateTime, req: &ServiceRequest) {
671        match self {
672            FormatText::RequestLine => {
673                *self = if req.query_string().is_empty() {
674                    FormatText::Str(format!(
675                        "{} {} {:?}",
676                        req.method(),
677                        req.path(),
678                        req.version()
679                    ))
680                } else {
681                    FormatText::Str(format!(
682                        "{} {}?{} {:?}",
683                        req.method(),
684                        req.path(),
685                        req.query_string(),
686                        req.version()
687                    ))
688                };
689            }
690            FormatText::UrlPath => *self = FormatText::Str(req.path().to_string()),
691            FormatText::RequestTime => *self = FormatText::Str(now.format(&Rfc3339).unwrap()),
692            FormatText::RequestHeader(ref name) => {
693                let s = if let Some(val) = req.headers().get(name) {
694                    String::from_utf8_lossy(val.as_bytes()).into_owned()
695                } else {
696                    "-".to_owned()
697                };
698                *self = FormatText::Str(s);
699            }
700            FormatText::RemoteAddr => {
701                let s = if let Some(peer) = req.connection_info().peer_addr() {
702                    FormatText::Str((*peer).to_string())
703                } else {
704                    FormatText::Str("-".to_string())
705                };
706                *self = s;
707            }
708            FormatText::RealIpRemoteAddr => {
709                let s = if let Some(remote) = req.connection_info().realip_remote_addr() {
710                    FormatText::Str(remote.to_string())
711                } else {
712                    FormatText::Str("-".to_string())
713                };
714                *self = s;
715            }
716            FormatText::CustomRequest(_, request_fn) => {
717                let s = match request_fn {
718                    Some(f) => FormatText::Str(f.call(req)),
719                    None => FormatText::Str("-".to_owned()),
720                };
721
722                *self = s;
723            }
724            _ => {}
725        }
726    }
727}
728
729/// Converter to get a String from something that writes to a Formatter.
730pub(crate) struct FormatDisplay<'a>(&'a dyn Fn(&mut fmt::Formatter<'_>) -> Result<(), fmt::Error>);
731
732impl fmt::Display for FormatDisplay<'_> {
733    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
734        (self.0)(fmt)
735    }
736}
737
738#[cfg(test)]
739mod tests {
740    use std::future::ready;
741
742    use actix_service::IntoService;
743
744    use super::*;
745    use crate::{
746        http::{header, StatusCode},
747        test::{self, TestRequest},
748        HttpResponse,
749    };
750
751    #[tokio::test(flavor = "local")]
752    async fn test_logger() {
753        let srv = |req: ServiceRequest| {
754            ready(Ok(req.into_response(
755                HttpResponse::build(StatusCode::OK)
756                    .insert_header(("X-Test", "ttt"))
757                    .finish(),
758            )))
759        };
760        let logger = Logger::new("%% %{User-Agent}i %{X-Test}o %{HOME}e %D test");
761
762        let srv = logger.new_transform(srv.into_service()).await.unwrap();
763
764        let req = TestRequest::default()
765            .insert_header((
766                header::USER_AGENT,
767                header::HeaderValue::from_static("ACTIX-WEB"),
768            ))
769            .to_srv_request();
770        let _res = srv.call(req).await;
771    }
772
773    #[tokio::test(flavor = "local")]
774    async fn test_logger_exclude_regex() {
775        let srv = |req: ServiceRequest| {
776            ready(Ok(req.into_response(
777                HttpResponse::build(StatusCode::OK)
778                    .insert_header(("X-Test", "ttt"))
779                    .finish(),
780            )))
781        };
782        let logger =
783            Logger::new("%% %{User-Agent}i %{X-Test}o %{HOME}e %D test").exclude_regex("\\w");
784
785        let srv = logger.new_transform(srv.into_service()).await.unwrap();
786
787        let req = TestRequest::default()
788            .insert_header((
789                header::USER_AGENT,
790                header::HeaderValue::from_static("ACTIX-WEB"),
791            ))
792            .to_srv_request();
793        let _res = srv.call(req).await.unwrap();
794    }
795
796    #[tokio::test(flavor = "local")]
797    async fn test_escape_percent() {
798        let mut format = Format::new("%%{r}a");
799
800        let req = TestRequest::default()
801            .insert_header((
802                header::FORWARDED,
803                header::HeaderValue::from_static("for=192.0.2.60;proto=http;by=203.0.113.43"),
804            ))
805            .to_srv_request();
806
807        let now = OffsetDateTime::now_utc();
808        for unit in &mut format.0 {
809            unit.render_request(now, &req);
810        }
811
812        let req = TestRequest::default().to_http_request();
813        let res = ServiceResponse::new(req, HttpResponse::Ok().finish());
814        for unit in &mut format.0 {
815            unit.render_response(&res);
816        }
817
818        let entry_time = OffsetDateTime::now_utc();
819        let render = |fmt: &mut fmt::Formatter<'_>| {
820            for unit in &format.0 {
821                unit.render(fmt, 1024, entry_time)?;
822            }
823            Ok(())
824        };
825        let s = format!("{}", FormatDisplay(&render));
826        assert_eq!(s, "%{r}a");
827    }
828
829    #[tokio::test(flavor = "local")]
830    async fn test_unknown_remote_addr_key() {
831        let mut format = Format::new("%{x}a %s");
832
833        let req = TestRequest::default().to_srv_request();
834        let now = OffsetDateTime::now_utc();
835        for unit in &mut format.0 {
836            unit.render_request(now, &req);
837        }
838
839        let req = TestRequest::default().to_http_request();
840        let res = ServiceResponse::new(req, HttpResponse::Ok().finish());
841        for unit in &mut format.0 {
842            unit.render_response(&res);
843        }
844
845        let entry_time = OffsetDateTime::now_utc();
846        let render = |fmt: &mut fmt::Formatter<'_>| {
847            for unit in &format.0 {
848                unit.render(fmt, 1024, entry_time)?;
849            }
850            Ok(())
851        };
852        let s = format!("{}", FormatDisplay(&render));
853        assert_eq!(s, "%{x}a 200");
854    }
855
856    #[tokio::test(flavor = "local")]
857    async fn test_url_path() {
858        let mut format = Format::new("%T %U");
859        let req = TestRequest::default()
860            .insert_header((
861                header::USER_AGENT,
862                header::HeaderValue::from_static("ACTIX-WEB"),
863            ))
864            .uri("/test/route/yeah")
865            .to_srv_request();
866
867        let now = OffsetDateTime::now_utc();
868        for unit in &mut format.0 {
869            unit.render_request(now, &req);
870        }
871
872        let req = TestRequest::default().to_http_request();
873        let res = ServiceResponse::new(req, HttpResponse::Ok().force_close().finish());
874        for unit in &mut format.0 {
875            unit.render_response(&res);
876        }
877
878        let render = |fmt: &mut fmt::Formatter<'_>| {
879            for unit in &format.0 {
880                unit.render(fmt, 1024, now)?;
881            }
882            Ok(())
883        };
884        let s = format!("{}", FormatDisplay(&render));
885        assert!(s.contains("/test/route/yeah"));
886    }
887
888    #[tokio::test(flavor = "local")]
889    async fn test_default_format() {
890        let mut format = Format::default();
891
892        let req = TestRequest::default()
893            .insert_header((
894                header::USER_AGENT,
895                header::HeaderValue::from_static("ACTIX-WEB"),
896            ))
897            .peer_addr("127.0.0.1:8081".parse().unwrap())
898            .to_srv_request();
899
900        let now = OffsetDateTime::now_utc();
901        for unit in &mut format.0 {
902            unit.render_request(now, &req);
903        }
904
905        let req = TestRequest::default().to_http_request();
906        let res = ServiceResponse::new(req, HttpResponse::Ok().force_close().finish());
907        for unit in &mut format.0 {
908            unit.render_response(&res);
909        }
910
911        let entry_time = OffsetDateTime::now_utc();
912        let render = |fmt: &mut fmt::Formatter<'_>| {
913            for unit in &format.0 {
914                unit.render(fmt, 1024, entry_time)?;
915            }
916            Ok(())
917        };
918        let s = format!("{}", FormatDisplay(&render));
919        assert!(s.contains("GET / HTTP/1.1"));
920        assert!(s.contains("127.0.0.1"));
921        assert!(s.contains("200 1024"));
922        assert!(s.contains("ACTIX-WEB"));
923    }
924
925    #[tokio::test(flavor = "local")]
926    async fn test_request_time_format() {
927        let mut format = Format::new("%t");
928        let req = TestRequest::default().to_srv_request();
929
930        let now = OffsetDateTime::now_utc();
931        for unit in &mut format.0 {
932            unit.render_request(now, &req);
933        }
934
935        let req = TestRequest::default().to_http_request();
936        let res = ServiceResponse::new(req, HttpResponse::Ok().force_close().finish());
937        for unit in &mut format.0 {
938            unit.render_response(&res);
939        }
940
941        let render = |fmt: &mut fmt::Formatter<'_>| {
942            for unit in &format.0 {
943                unit.render(fmt, 1024, now)?;
944            }
945            Ok(())
946        };
947        let s = format!("{}", FormatDisplay(&render));
948        assert!(s.contains(&now.format(&Rfc3339).unwrap()));
949    }
950
951    #[tokio::test(flavor = "local")]
952    async fn test_remote_addr_format() {
953        let mut format = Format::new("%{r}a");
954
955        let req = TestRequest::default()
956            .insert_header((
957                header::FORWARDED,
958                header::HeaderValue::from_static("for=192.0.2.60;proto=http;by=203.0.113.43"),
959            ))
960            .to_srv_request();
961
962        let now = OffsetDateTime::now_utc();
963        for unit in &mut format.0 {
964            unit.render_request(now, &req);
965        }
966
967        let req = TestRequest::default().to_http_request();
968        let res = ServiceResponse::new(req, HttpResponse::Ok().finish());
969        for unit in &mut format.0 {
970            unit.render_response(&res);
971        }
972
973        let entry_time = OffsetDateTime::now_utc();
974        let render = |fmt: &mut fmt::Formatter<'_>| {
975            for unit in &format.0 {
976                unit.render(fmt, 1024, entry_time)?;
977            }
978            Ok(())
979        };
980        let s = format!("{}", FormatDisplay(&render));
981        assert!(s.contains("192.0.2.60"));
982    }
983
984    #[tokio::test(flavor = "local")]
985    async fn test_custom_closure_req_log() {
986        let mut logger = Logger::new("test %{CUSTOM}xi")
987            .custom_request_replace("CUSTOM", |_req: &ServiceRequest| -> String {
988                String::from("custom_log")
989            });
990        let mut unit = Rc::get_mut(&mut logger.0).unwrap().format.0[1].clone();
991
992        let label = match &unit {
993            FormatText::CustomRequest(label, _) => label,
994            ft => panic!("Expected CustomRequest, found {:?}", ft),
995        };
996
997        assert_eq!(label, "CUSTOM");
998
999        let req = TestRequest::default().to_srv_request();
1000        let now = OffsetDateTime::now_utc();
1001
1002        unit.render_request(now, &req);
1003
1004        let render = |fmt: &mut fmt::Formatter<'_>| unit.render(fmt, 1024, now);
1005
1006        let log_output = FormatDisplay(&render).to_string();
1007        assert_eq!(log_output, "custom_log");
1008    }
1009
1010    #[tokio::test(flavor = "local")]
1011    async fn test_custom_closure_response_log() {
1012        let mut logger = Logger::new("test %{CUSTOM}xo").custom_response_replace(
1013            "CUSTOM",
1014            |res: &ServiceResponse| -> String {
1015                if res.status().as_u16() == 200 {
1016                    String::from("custom_log")
1017                } else {
1018                    String::from("-")
1019                }
1020            },
1021        );
1022        let mut unit = Rc::get_mut(&mut logger.0).unwrap().format.0[1].clone();
1023
1024        let label = match &unit {
1025            FormatText::CustomResponse(label, _) => label,
1026            ft => panic!("Expected CustomResponse, found {:?}", ft),
1027        };
1028
1029        assert_eq!(label, "CUSTOM");
1030
1031        let req = TestRequest::default().to_http_request();
1032        let resp_ok = ServiceResponse::new(req, HttpResponse::Ok().finish());
1033        let now = OffsetDateTime::now_utc();
1034        unit.render_response(&resp_ok);
1035
1036        let render = |fmt: &mut fmt::Formatter<'_>| unit.render(fmt, 1024, now);
1037
1038        let log_output = FormatDisplay(&render).to_string();
1039        assert_eq!(log_output, "custom_log");
1040    }
1041
1042    #[tokio::test(flavor = "local")]
1043    async fn test_closure_logger_in_middleware() {
1044        let captured = "custom log replacement";
1045
1046        let logger = Logger::new("%{CUSTOM}xi")
1047            .custom_request_replace("CUSTOM", move |_req: &ServiceRequest| -> String {
1048                captured.to_owned()
1049            });
1050
1051        let srv = logger.new_transform(test::ok_service()).await.unwrap();
1052
1053        let req = TestRequest::default().to_srv_request();
1054        srv.call(req).await.unwrap();
1055    }
1056}