Single-binary self-hosted website analytics on Rust axum: collector API, dashboards, world map, and PDF reports.
analyticsaxumdockerrustself-hostedsqliteviteweb-analytics
1use axum::{
2 extract::Request,
3 http::StatusCode,
4 middleware::Next,
5 response::{IntoResponse, Response},
6};
7use chrono::Local;
8use std::time::Instant;
9
10pub async fn log_requests(req: Request, next: Next) -> Response {
11 let method = req.method().clone();
12 let path = req
13 .uri()
14 .path_and_query()
15 .map(|p| p.as_str().to_string())
16 .unwrap_or_else(|| req.uri().path().to_string());
17 let start = Instant::now();
18 let response = next.run(req).await;
19 let elapsed_ms = start.elapsed().as_secs_f64() * 1000.0;
20 let status = response.status().as_u16();
21 let now = Local::now().format("%H:%M:%S");
22 let color = match status {
23 200..=299 => "\x1b[32m",
24 300..=399 => "\x1b[36m",
25 400..=499 => "\x1b[33m",
26 _ => "\x1b[31m",
27 };
28 eprintln!("{now} {method:<5} {color}{status}\x1b[0m {elapsed_ms:>7.2}ms {path}");
29 response
30}
31
32pub async fn not_found() -> Response {
33 (StatusCode::NOT_FOUND, "404 Not Found").into_response()
34}