10

Is there a way to log all requests being received by actix-web irrespective of whether the endpoint exists or not?

It seems I need to use middleware for this, is this the recommended approach?

BinaryButterfly
  • 18,137
  • 13
  • 50
  • 91
Allan K
  • 379
  • 2
  • 13

1 Answers1

9

There is logging middleware available as part of actix_web: actix_web::middleware::Logger

Middleware for logging request and response info to the terminal. Logger middleware uses standard log crate to log information.

Middleware is called for each request (so long no other middleware or route handles it beforehand), so putting it on your App at the top level should get all requests, whether the endpoint exists or not.

use actix_web::{middleware::Logger, App};

let app = App::new()
    .wrap(Logger::default())
    // ...
kmdreko
  • 42,554
  • 6
  • 57
  • 106
  • 2
    You need to enable a logging implementation too: `env_logger::init_from_env(env_logger::Env::new().default_filter_or("info"));` – jrpear May 26 '23 at 17:12
  • @jrpear Right, I forget that not everyone knows the `log` crate just provides a facade and you need to initialize a logging implementation of your choosing based on where and how the log messages should be sent. Env-logger is a common one but others can be seen at: [available logging implementations](https://docs.rs/log/latest/log/#available-logging-implementations). – kmdreko May 26 '23 at 19:29
  • I've made a fork of the original logger in this crate [actix-contrib-logger](https://crates.io/crates/actix-contrib-logger), that allows to customize a bit more the level to print out HTTP requests, and the errors in the requests as well. Moreover, by default server errors (HTTP 5xx) are printed with `ERROR` severity. – Mariano Ruiz Aug 14 '23 at 15:17