feat(telemetry): add axum_middleware

This commit is contained in:
2026-01-30 16:28:29 +08:00
parent 4db955113c
commit 9465892cc6
5 changed files with 139 additions and 1 deletions

View File

@@ -2,6 +2,7 @@ use axum::{Router, body::Body, routing::get};
use common_telemetry::{
error::AppError,
response::AppResponse,
axum_middleware::trace_http_request,
telemetry::{self, TelemetryConfig},
};
use http::{Request, StatusCode};
@@ -237,3 +238,61 @@ async fn test_full_flow_error_and_logging() {
// temp_dir 会在作用域结束时自动删除清理
}
#[tokio::test]
async fn error_log_includes_http_context_span() {
use std::sync::{Arc, Mutex};
use tracing_subscriber::fmt::MakeWriter;
struct BufferWriter(Arc<Mutex<Vec<u8>>>);
impl<'a> MakeWriter<'a> for BufferWriter {
type Writer = BufferGuard;
fn make_writer(&'a self) -> Self::Writer {
BufferGuard(self.0.clone())
}
}
struct BufferGuard(Arc<Mutex<Vec<u8>>>);
impl std::io::Write for BufferGuard {
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
self.0.lock().unwrap().extend_from_slice(buf);
Ok(buf.len())
}
fn flush(&mut self) -> std::io::Result<()> {
Ok(())
}
}
async fn handler() -> Result<String, AppError> {
Err(AppError::MissingAuthHeader)
}
let buf = Arc::new(Mutex::new(Vec::<u8>::new()));
let subscriber = tracing_subscriber::fmt()
.with_writer(BufferWriter(buf.clone()))
.with_ansi(false)
.json()
.with_current_span(true)
.with_span_list(true)
.finish();
let _guard = tracing::subscriber::set_default(subscriber);
let app = Router::new()
.route("/needs-auth", get(handler))
.layer(axum::middleware::from_fn(trace_http_request));
let resp = app
.oneshot(
Request::builder()
.uri("/needs-auth")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
let logs = String::from_utf8(buf.lock().unwrap().clone()).unwrap();
assert!(logs.contains("\"message\":\"Request failed\""));
assert!(logs.contains("/needs-auth"));
assert!(logs.contains("http.method") || logs.contains("GET"));
}