Logging Middleware
Logging plays a crucial role in web applications, enabling:
- Detailed information about request processing, helping developers track application behavior
- Assistance with troubleshooting and debugging, especially in production environments
- Monitoring of application performance and resource usage
- Recording of user access patterns and system exceptions
- Meeting security audit and compliance requirements
Salvo provides middleware with basic logging functionality. If the middleware is added directly to a Router
, it won't be able to capture 404 errors returned when no Router
matches. It's recommended to add it to the Service
instead.
Example Code
logging/src/main.rs
use salvo::logging::Logger;
use salvo::prelude::*;
#[handler]
async fn hello() -> &'static str {
"Hello World"
}
#[tokio::main]
async fn main() {
tracing_subscriber::fmt().init();
let router = Router::new().get(hello);
let service = Service::new(router).hoop(Logger::new());
let acceptor = TcpListener::new("0.0.0.0:5800").bind().await;
Server::new(acceptor).serve(service).await;
}