use axum::body::{to_bytes, Body};
use axum::http::{header, StatusCode};
use axum::{extract::Request, response::Response};
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use std::task::{Context, Poll};
use std::time::Instant;
use tower::{Layer, Service};
use tracing::{info, warn};
const PRINT_BODY_MAX: usize = 4096;
const MAX_BUFFER_BODY: usize = 16 * 1024 * 1024;
const BODY_OVER_LIMIT_NOTE: &str = "(body 超过缓冲上限,未打印)";
#[derive(Clone)]
pub struct RequestLogLayer {
pub exclude_paths: Arc<Vec<String>>,
pub log_duration: bool,
pub print_body: bool,
pub report_multiline: bool,
}
impl Default for RequestLogLayer {
fn default() -> Self {
Self {
exclude_paths: Arc::new(vec!["/health".into(), "/favicon.ico".into()]),
log_duration: true,
print_body: false,
report_multiline: false,
}
}
}
impl RequestLogLayer {
pub fn new() -> Self {
Self::default()
}
pub fn exclude_paths(mut self, paths: Vec<String>) -> Self {
self.exclude_paths = Arc::new(paths);
self
}
}
impl<S> Layer<S> for RequestLogLayer {
type Service = RequestLogService<S>;
fn layer(&self, inner: S) -> Self::Service {
RequestLogService {
inner,
exclude_paths: self.exclude_paths.clone(),
log_duration: self.log_duration,
print_body: self.print_body,
report_multiline: self.report_multiline,
}
}
}
#[derive(Clone)]
pub struct RequestLogService<S> {
inner: S,
exclude_paths: Arc<Vec<String>>,
log_duration: bool,
print_body: bool,
report_multiline: bool,
}
impl<S> Service<Request<Body>> for RequestLogService<S>
where
S: Service<Request<Body>, Response = Response> + Clone + Send + 'static,
S::Future: Send + 'static,
S::Error: Send,
{
type Response = S::Response;
type Error = S::Error;
type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send>>;
fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
self.inner.poll_ready(cx)
}
fn call(&mut self, mut req: Request<Body>) -> Self::Future {
let path = req.uri().path().to_string();
let should_log = !self.exclude_paths.contains(&path);
let replacement = self.inner.clone();
let mut inner = std::mem::replace(&mut self.inner, replacement);
if !should_log {
return Box::pin(async move { inner.call(req).await });
}
let method = req.method().clone();
let ip = req
.extensions()
.get::<super::client_identity::ClientIp>()
.map(|c| c.0.clone())
.unwrap_or_else(|| "unknown".to_string());
let req_id = req
.extensions()
.get::<super::request_id::RequestId>()
.map(|r| r.0.clone())
.or_else(|| {
req.headers()
.get("x-request-id")
.and_then(|v| v.to_str().ok())
.map(|s| s.to_string())
})
.unwrap_or_else(|| "-".to_string());
let log_duration = self.log_duration;
let print_body = self.print_body;
let report_multiline = self.report_multiline;
let query_str = if print_body || report_multiline {
req.uri().query().map(|q| q.to_string()).unwrap_or_default()
} else {
String::new()
};
let start = Instant::now();
Box::pin(async move {
let req_snippet = if print_body {
match collect_request_body(&mut req, MAX_BUFFER_BODY).await {
Ok(snippet) => snippet,
Err(resp) => {
warn!(
request_id = %req_id, ip = %ip,
"{method} {path} -> 413 (调试日志请求体超出缓冲上限)"
);
return Ok(resp);
}
}
} else {
String::new()
};
let mut result = inner.call(req).await;
let resp_snippet = if print_body {
match &mut result {
Ok(resp) => collect_response_body(resp, MAX_BUFFER_BODY).await,
Err(_) => String::new(),
}
} else {
String::new()
};
let elapsed = start.elapsed();
let duration_ms = elapsed.as_millis();
let duration_str = if log_duration {
format!("{duration_ms}ms")
} else {
String::new()
};
if report_multiline {
let (status_text, is_err) = match &result {
Ok(response) => {
let reason = response
.status()
.canonical_reason()
.unwrap_or("");
(
format!("{} {}", response.status().as_u16(), reason),
false,
)
}
Err(_e) => ("ERR".to_string(), true),
};
let report = build_report(
method.as_str(),
&path,
&query_str,
&status_text,
&duration_str,
&ip,
&req_id,
&req_snippet,
&resp_snippet,
print_body,
);
if is_err {
warn!(request_id = %req_id, ip = %ip, "{report}");
} else {
info!(request_id = %req_id, ip = %ip, "{report}");
}
return result;
}
let duration_paren = if duration_str.is_empty() {
String::new()
} else {
format!(" ({duration_str})")
};
let req_debug = if print_body && (!query_str.is_empty() || !req_snippet.is_empty()) {
if query_str.is_empty() {
format!(" req={req_snippet}")
} else if req_snippet.is_empty() {
format!(" req=?{query_str}")
} else {
format!(" req=?{query_str} {req_snippet}")
}
} else {
String::new()
};
let resp_debug = if print_body && !resp_snippet.is_empty() {
format!(" resp={resp_snippet}")
} else {
String::new()
};
match &result {
Ok(response) => {
let status = response.status().as_u16();
if status >= 500 {
warn!(
request_id = %req_id, ip = %ip,
"{method} {path} -> {status}{duration_paren}{req_debug}{resp_debug}"
);
} else {
info!(
request_id = %req_id, ip = %ip,
"{method} {path} -> {status}{duration_paren}{req_debug}{resp_debug}"
);
}
}
Err(_e) => {
warn!(
request_id = %req_id, ip = %ip,
"{method} {path} -> ERR{duration_paren}{req_debug}{resp_debug}"
);
}
}
result
})
}
}
fn body_snippet(bytes: &[u8]) -> String {
if bytes.len() <= PRINT_BODY_MAX {
return String::from_utf8_lossy(bytes).into_owned();
}
let cut = bytes.len().min(PRINT_BODY_MAX * 4);
let text = String::from_utf8_lossy(&bytes[..cut]);
let truncated: String = text.chars().take(PRINT_BODY_MAX).collect();
format!("{truncated}...(truncated {})", bytes.len())
}
async fn collect_request_body(req: &mut Request<Body>, cap: usize) -> Result<String, Response> {
let taken = std::mem::take(req);
let (parts, body) = taken.into_parts();
let declared_len = parts
.headers
.get(header::CONTENT_LENGTH)
.and_then(|v| v.to_str().ok())
.and_then(|v| v.parse::<usize>().ok());
if declared_len.is_some_and(|n| n > cap) {
*req = Request::from_parts(parts, body);
return Ok(BODY_OVER_LIMIT_NOTE.to_string());
}
match to_bytes(body, cap).await {
Ok(bytes) => {
let snippet = body_snippet(&bytes);
*req = Request::from_parts(parts, Body::from(bytes));
Ok(snippet)
}
Err(e) => {
tracing::error!(
err = %e,
"调试日志收集请求体超出缓冲上限({cap}B),body 已不可恢复,返回 413"
);
Err(Response::builder()
.status(StatusCode::PAYLOAD_TOO_LARGE)
.header(header::CONTENT_TYPE, "text/plain; charset=utf-8")
.body(Body::from("request body too large"))
.expect("固定 413 响应构建不会失败"))
}
}
}
async fn collect_response_body(resp: &mut Response, cap: usize) -> String {
let declared_len = resp
.headers()
.get(header::CONTENT_LENGTH)
.and_then(|v| v.to_str().ok())
.and_then(|v| v.parse::<usize>().ok());
if declared_len.is_some_and(|n| n > cap) {
return BODY_OVER_LIMIT_NOTE.to_string();
}
let body = std::mem::replace(resp.body_mut(), Body::empty());
match to_bytes(body, cap).await {
Ok(bytes) => {
let snippet = body_snippet(&bytes);
*resp.body_mut() = Body::from(bytes);
snippet
}
Err(e) => {
tracing::error!(
err = %e,
"调试日志收集响应体超出缓冲上限({cap}B),响应体已不可恢复"
);
resp.headers_mut().remove(header::CONTENT_LENGTH);
"(响应体超过缓冲上限,已丢失)".to_string()
}
}
}
#[allow(clippy::too_many_arguments)]
fn build_report(
method: &str,
path: &str,
query: &str,
status_text: &str,
duration: &str,
ip: &str,
req_id: &str,
req_snippet: &str,
resp_snippet: &str,
print_body: bool,
) -> String {
const LINE: &str = "=============================== REQUEST ===============================";
let mut s = format!("{LINE}\n");
s.push_str(&format!(" {status_text:8} {method} {path}"));
if !query.is_empty() {
s.push_str(&format!("?{query}"));
}
let now = wordval_utils::Date::now_local().format("%Y-%m-%d %H:%M:%S%.3f");
s.push_str(&format!("\n TIME {now}"));
let duration_part = if duration.is_empty() {
String::new()
} else {
format!("{duration:>8}")
};
s.push_str(&format!("\n DURATION {duration_part} IP {ip:>15} REQ-ID {req_id}"));
if print_body && !req_snippet.is_empty() {
s.push_str(&format!("\n BODY {req_snippet}"));
}
if print_body && !resp_snippet.is_empty() {
s.push_str(&format!("\n RESULT {resp_snippet}"));
}
s.push('\n');
s.push_str(LINE);
s
}