Logging Middleware

Logging plays a crucial role in web applications, as it enables:

  • Providing detailed information about the request handling process to help developers track application behavior
  • Assisting in troubleshooting and debugging, especially in production environments
  • Monitoring application performance and resource usage
  • Recording user access patterns and system exceptions
  • Meeting security auditing and compliance requirements

Salvo provides a middleware with basic logging functionality. If the middleware is added directly to a Router, it will not capture 404 errors returned when no Router matches the request. It is recommended to add it to the Service instead.

Example Code

main.rs
Cargo.toml
use salvo::logging::Logger;
use salvo::prelude::*;

#[handler]
async fn hello() -> &'static str {
    "Hello World"
}

#[handler]
async fn error() -> StatusError {
    StatusError::bad_request()
        .brief("Bad request error")
        .detail("The request was malformed.")
}

#[tokio::main]
async fn main() {
    tracing_subscriber::fmt().init();

    let router = Router::new()
        .get(hello)
        .push(Router::with_path("error").get(error));
    let service = Service::new(router).hoop(Logger::new());

    let acceptor = TcpListener::new("0.0.0.0:8698").bind().await;
    Server::new(acceptor).serve(service).await;
}