use std::{
borrow::Cow,
cell::Cell,
fmt::{self, Display},
sync::{
Arc,
atomic::{AtomicU64, Ordering},
},
time::{Duration, Instant},
};
use axum::{
Router,
extract::{MatchedPath, Request, State},
http::{HeaderName, HeaderValue, Method, Response, StatusCode, Uri},
middleware::{self, Next},
response::Response as AxumResponse,
};
use serde::{Serialize, Serializer, ser::SerializeMap};
use thiserror::Error;
use tower_http::catch_panic::CatchPanicLayer;
use super::{
OperationKind, RequestId, RequestLogContext, RequestLoggingLimits, RequestSubject,
TrustedSubject,
context::scope_request_log,
json_format::{ERROR_FIELD, REQUEST_CONTEXT_FIELD, REQUEST_HEADERS_FIELD},
panic_recovery::{PanicRecoveryConfig, response_for_panic},
};
use crate::web::response::ErrorLogMetadata;
const SUCCESS_SAMPLE_SCALE: u64 = 1_u64 << 53;
const SUCCESS_SAMPLE_SCALE_FLOAT: f64 = 9_007_199_254_740_992.0;
const SAMPLE_THREAD_SEED_INCREMENT: u64 = 0x9e37_79b9_7f4a_7c15;
static SAMPLE_THREAD_SEED: AtomicU64 = AtomicU64::new(SAMPLE_THREAD_SEED_INCREMENT);
thread_local! {
static SAMPLE_STATE: Cell<u64> = Cell::new(mix_sample_value(
SAMPLE_THREAD_SEED.fetch_add(SAMPLE_THREAD_SEED_INCREMENT, Ordering::Relaxed),
));
}
struct RequestContextJson<'context>(&'context RequestLogContext);
impl Display for RequestContextJson<'_> {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
write_json(formatter, self.0)
}
}
#[derive(Clone, Debug)]
#[must_use = "配置需要传给 RouterLoggingExt 才会生效"]
#[allow(clippy::struct_excessive_bools)]
pub struct RequestLoggingConfig {
request_id_header: HeaderName,
request_id_max_length: usize,
trusted_subject_header: Option<HeaderName>,
trusted_subject_kind: Option<String>,
trusted_subject_max_length: usize,
included_headers: Vec<HeaderName>,
redacted_headers: Vec<HeaderName>,
include_query: bool,
panic_recovery: Option<PanicRecoveryConfig>,
skipped_success_paths: Vec<String>,
skipped_success_prefixes: Vec<String>,
slow_request_threshold: Option<Duration>,
success_sample_threshold: u64,
always_log_errors: bool,
quiet_queries: bool,
log_slow_queries: bool,
always_log_commands: bool,
expose_context_in_response: bool,
limits: RequestLoggingLimits,
}
impl Default for RequestLoggingConfig {
fn default() -> Self {
Self {
request_id_header: HeaderName::from_static("x-request-id"),
request_id_max_length: 128,
trusted_subject_header: None,
trusted_subject_kind: None,
trusted_subject_max_length: 128,
included_headers: Vec::new(),
redacted_headers: vec![
HeaderName::from_static("authorization"),
HeaderName::from_static("cookie"),
HeaderName::from_static("set-cookie"),
HeaderName::from_static("x-api-key"),
],
include_query: false,
panic_recovery: Some(PanicRecoveryConfig::default()),
skipped_success_paths: vec!["/health".into(), "/metrics".into()],
skipped_success_prefixes: vec!["/static/".into()],
slow_request_threshold: Some(Duration::from_millis(400)),
success_sample_threshold: SUCCESS_SAMPLE_SCALE,
always_log_errors: true,
quiet_queries: false,
log_slow_queries: true,
always_log_commands: false,
expose_context_in_response: false,
limits: RequestLoggingLimits::default(),
}
}
}
#[derive(Clone, Debug, Error, Eq, PartialEq)]
pub enum RequestLoggingConfigError {
#[error("{name}必须大于 0")]
NonPositive { name: &'static str },
#[error("成功请求日志采样率必须是 0.0 到 1.0 之间的有限数值")]
InvalidSampleRate,
}
impl RequestLoggingConfig {
pub fn new() -> Self {
Self::default()
}
pub fn with_request_id_header(mut self, header: HeaderName) -> Self {
self.request_id_header = header;
self
}
pub fn request_id_max_length(mut self, max_length: usize) -> Self {
assert!(max_length > 0, "请求 ID 最大长度必须大于 0");
self.request_id_max_length = max_length;
self
}
pub fn try_request_id_max_length(
mut self,
max_length: usize,
) -> Result<Self, RequestLoggingConfigError> {
if max_length == 0 {
return Err(RequestLoggingConfigError::NonPositive {
name: "请求 ID 最大长度",
});
}
self.request_id_max_length = max_length;
Ok(self)
}
pub fn trusted_subject_header(mut self, header: HeaderName) -> Self {
self.trusted_subject_header = Some(header);
self
}
pub fn without_trusted_subject(mut self) -> Self {
self.trusted_subject_header = None;
self.trusted_subject_kind = None;
self
}
pub fn trusted_subject_kind(mut self, kind: impl Into<String>) -> Self {
self.trusted_subject_kind = Some(kind.into());
self
}
pub fn trusted_subject_max_length(mut self, max_length: usize) -> Self {
assert!(max_length > 0, "可信主体 ID 最大长度必须大于 0");
self.trusted_subject_max_length = max_length;
self
}
pub fn try_trusted_subject_max_length(
mut self,
max_length: usize,
) -> Result<Self, RequestLoggingConfigError> {
if max_length == 0 {
return Err(RequestLoggingConfigError::NonPositive {
name: "可信主体 ID 最大长度",
});
}
self.trusted_subject_max_length = max_length;
Ok(self)
}
pub fn include_header(mut self, header: HeaderName) -> Self {
if !self.included_headers.contains(&header) {
self.included_headers.push(header);
}
self
}
pub fn include_headers<I>(mut self, headers: I) -> Self
where
I: IntoIterator<Item = HeaderName>,
{
for header in headers {
if !self.included_headers.contains(&header) {
self.included_headers.push(header);
}
}
self
}
pub fn without_headers(mut self) -> Self {
self.included_headers.clear();
self
}
pub fn redact_header(mut self, header: HeaderName) -> Self {
if !self.redacted_headers.contains(&header) {
self.redacted_headers.push(header);
}
self
}
pub const fn include_query(mut self, include: bool) -> Self {
self.include_query = include;
self
}
pub fn skip_success_path(mut self, path: impl Into<String>) -> Self {
let path = path.into();
if !self.skipped_success_paths.contains(&path) {
self.skipped_success_paths.push(path);
}
self
}
pub fn skip_success_prefix(mut self, prefix: impl Into<String>) -> Self {
let prefix = prefix.into();
if !self.skipped_success_prefixes.contains(&prefix) {
self.skipped_success_prefixes.push(prefix);
}
self
}
pub fn clear_skipped_success_paths(mut self) -> Self {
self.skipped_success_paths.clear();
self
}
pub fn clear_skipped_success_prefixes(mut self) -> Self {
self.skipped_success_prefixes.clear();
self
}
pub const fn slow_request_threshold(mut self, threshold: Duration) -> Self {
self.slow_request_threshold = Some(threshold);
self
}
pub const fn without_slow_request_threshold(mut self) -> Self {
self.slow_request_threshold = None;
self
}
pub fn success_sample_rate(mut self, rate: f64) -> Self {
assert!(
(0.0..=1.0).contains(&rate),
"成功请求日志采样率必须在 0.0 到 1.0 之间"
);
self.success_sample_threshold = success_sample_threshold(rate);
self
}
pub fn try_success_sample_rate(mut self, rate: f64) -> Result<Self, RequestLoggingConfigError> {
if !rate.is_finite() || !(0.0..=1.0).contains(&rate) {
return Err(RequestLoggingConfigError::InvalidSampleRate);
}
self.success_sample_threshold = success_sample_threshold(rate);
Ok(self)
}
pub const fn always_log_errors(mut self, always: bool) -> Self {
self.always_log_errors = always;
self
}
pub const fn quiet_queries(mut self, quiet: bool) -> Self {
self.quiet_queries = quiet;
self
}
pub const fn log_slow_queries(mut self, enabled: bool) -> Self {
self.log_slow_queries = enabled;
self
}
pub const fn always_log_commands(mut self, always: bool) -> Self {
self.always_log_commands = always;
self
}
pub const fn expose_context_in_response(mut self, expose: bool) -> Self {
self.expose_context_in_response = expose;
self
}
pub const fn with_limits(mut self, limits: RequestLoggingLimits) -> Self {
self.limits = limits;
self
}
pub fn with_panic_recovery_config(mut self, config: PanicRecoveryConfig) -> Self {
self.panic_recovery = Some(config);
self
}
pub fn without_panic_recovery(mut self) -> Self {
self.panic_recovery = None;
self
}
fn should_skip_success(&self, metadata: &RequestLogMetadata) -> bool {
let path = metadata.uri.path();
let route = metadata.route.as_ref().map(MatchedPath::as_str);
self.skipped_success_paths
.iter()
.any(|skipped| skipped == path || route.is_some_and(|route| skipped == route))
|| self.skipped_success_prefixes.iter().any(|prefix| {
path.starts_with(prefix) || route.is_some_and(|route| route.starts_with(prefix))
})
}
fn is_slow_request(&self, latency: Duration) -> bool {
self.slow_request_threshold
.is_some_and(|threshold| latency >= threshold)
}
fn should_sample_success(&self) -> bool {
if self.success_sample_threshold == SUCCESS_SAMPLE_SCALE {
return true;
}
if self.success_sample_threshold == 0 {
return false;
}
let value = next_sample_value();
(value >> 11) < self.success_sample_threshold
}
}
const fn mix_sample_value(mut value: u64) -> u64 {
value = (value ^ (value >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9);
value = (value ^ (value >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb);
value ^ (value >> 31)
}
fn next_sample_value() -> u64 {
SAMPLE_STATE.with(|state| {
let mut value = state.get();
value ^= value >> 12;
value ^= value << 25;
value ^= value >> 27;
state.set(value);
value.wrapping_mul(0x2545_f491_4f6c_dd1d)
})
}
#[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
fn success_sample_threshold(rate: f64) -> u64 {
(rate * SUCCESS_SAMPLE_SCALE_FLOAT).round() as u64
}
struct RequestLogMetadata {
method: Method,
uri: Uri,
route: Option<MatchedPath>,
request_id: RequestId,
request_id_header_value: HeaderValue,
headers: Vec<CapturedHeader>,
max_header_value_bytes: usize,
}
struct CapturedHeader {
name: HeaderName,
value: HeaderValue,
redacted: bool,
}
impl RequestLogMetadata {
fn from_request<B>(
request: &mut axum::http::Request<B>,
config: &RequestLoggingConfig,
request_log: Option<&RequestLogContext>,
) -> Self {
let request_id = request
.headers()
.get(&config.request_id_header)
.and_then(|value| value.to_str().ok())
.map(str::trim)
.filter(|value| !value.is_empty() && value.len() <= config.request_id_max_length)
.map_or_else(
|| RequestId::new(uuid::Uuid::now_v7().to_string()),
|value| RequestId::new(value.to_owned()),
);
let request_id_header_value = HeaderValue::from_str(request_id.as_str())
.expect("UUID 或已校验的请求 ID 始终是合法请求头值");
let trusted_subject = config
.trusted_subject_header
.as_ref()
.and_then(|header| request.headers().get(header))
.and_then(|value| value.to_str().ok())
.map(str::trim)
.filter(|value| !value.is_empty() && value.len() <= config.trusted_subject_max_length)
.map(|value| {
let mut subject = RequestSubject::new(value);
if let Some(kind) = &config.trusted_subject_kind {
subject = subject.with_kind(kind.clone());
}
subject
});
let headers = config
.included_headers
.iter()
.filter_map(|name| {
request
.headers()
.get(name)
.filter(|value| value.to_str().is_ok())
.map(|value| CapturedHeader {
name: name.clone(),
value: value.clone(),
redacted: config.redacted_headers.contains(name),
})
})
.collect();
request.extensions_mut().insert(request_id.clone());
if let Some(subject) = trusted_subject {
if let Some(request_log) = request_log {
request_log.set_subject(subject.clone());
}
request
.extensions_mut()
.insert(TrustedSubject::new(subject));
}
Self {
method: request.method().clone(),
uri: request.uri().clone(),
route: request.extensions().get::<MatchedPath>().cloned(),
request_id,
request_id_header_value,
headers,
max_header_value_bytes: config.limits.max_header_value_bytes,
}
}
fn route(&self) -> &str {
self.route
.as_ref()
.map_or_else(|| self.uri.path(), MatchedPath::as_str)
}
fn request_id(&self) -> &str {
self.request_id.as_str()
}
fn headers_for_log(&self) -> Option<RequestHeadersJson<'_>> {
(!self.headers.is_empty()).then_some(RequestHeadersJson {
headers: &self.headers,
max_value_bytes: self.max_header_value_bytes,
})
}
}
struct RequestHeadersJson<'headers> {
headers: &'headers [CapturedHeader],
max_value_bytes: usize,
}
impl Serialize for RequestHeadersJson<'_> {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let mut map = serializer.serialize_map(None)?;
for captured in self.headers {
let raw_value = if captured.redacted {
"[已脱敏]"
} else {
captured.value.to_str().expect("捕获请求头时已校验 UTF-8")
};
if raw_value.len() <= self.max_value_bytes {
map.serialize_entry(captured.name.as_str(), raw_value)?;
} else {
let mut truncated = raw_value.to_owned();
super::context::truncate_utf8(&mut truncated, self.max_value_bytes);
map.serialize_entry(captured.name.as_str(), &truncated)?;
}
}
map.end()
}
}
impl Display for RequestHeadersJson<'_> {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
write_json(formatter, self)
}
}
struct ErrorJson<'error>(&'error ErrorLogMetadata);
impl Display for ErrorJson<'_> {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
write_json(formatter, self.0)
}
}
struct RequestUri<'a> {
uri: &'a Uri,
include_query: bool,
max_bytes: usize,
}
impl Display for RequestUri<'_> {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let raw = if self.include_query {
Cow::Owned(self.uri.to_string())
} else {
Cow::Borrowed(self.uri.path())
};
if raw.len() <= self.max_bytes {
formatter.write_str(raw.as_ref())
} else {
let mut truncated = raw.into_owned();
super::context::truncate_utf8(&mut truncated, self.max_bytes);
formatter.write_str(&truncated)
}
}
}
#[derive(Clone, Copy)]
enum RequestEventLevel {
Info,
Warn,
Error,
}
impl RequestEventLevel {
fn is_enabled(self) -> bool {
match self {
Self::Info => tracing::event_enabled!(tracing::Level::INFO),
Self::Warn => tracing::event_enabled!(tracing::Level::WARN),
Self::Error => tracing::event_enabled!(tracing::Level::ERROR),
}
}
}
struct RequestEvent<'a> {
metadata: &'a RequestLogMetadata,
include_query: bool,
max_uri_bytes: usize,
status: StatusCode,
handler_latency_ms: f64,
is_slow: bool,
operation_kind: &'static str,
outcome: &'static str,
request_context: Option<&'a RequestLogContext>,
}
macro_rules! emit_request_event {
($level:expr, $event:expr; $($extra:tt)*) => {{
let uri = RequestUri {
uri: &$event.metadata.uri,
include_query: $event.include_query,
max_bytes: $event.max_uri_bytes,
};
let headers = $event
.metadata
.headers_for_log()
.map(tracing::field::display);
let request_context = $event
.request_context
.map(RequestContextJson)
.map(tracing::field::display);
tracing::event!(
$level,
method = %$event.metadata.method,
route = %$event.metadata.route(),
path = %$event.metadata.uri.path(),
uri = %uri,
request_id = %$event.metadata.request_id(),
event = "request.completed",
operation_kind = $event.operation_kind,
{ REQUEST_HEADERS_FIELD } = headers,
status = $event.status.as_u16(),
outcome = $event.outcome,
handler_latency_ms = $event.handler_latency_ms,
slow_request = $event.is_slow,
{ REQUEST_CONTEXT_FIELD } = request_context,
$($extra)*
"请求处理完成"
);
}};
}
pub trait RouterLoggingExt<S> {
fn with_request_logging(self) -> Router<S>;
fn with_request_logging_config(self, config: RequestLoggingConfig) -> Router<S>;
fn with_access_logging(self) -> Router<S>;
fn with_access_logging_config(self, config: RequestLoggingConfig) -> Router<S>;
}
impl<S> RouterLoggingExt<S> for Router<S>
where
S: Clone + Send + Sync + 'static,
{
fn with_request_logging(self) -> Self {
self.with_request_logging_config(RequestLoggingConfig::default())
}
fn with_request_logging_config(self, config: RequestLoggingConfig) -> Self {
install_request_logging(self, config, true)
}
fn with_access_logging(self) -> Self {
self.with_access_logging_config(RequestLoggingConfig::default())
}
fn with_access_logging_config(self, config: RequestLoggingConfig) -> Self {
install_request_logging(self, config, false)
}
}
fn install_request_logging<S>(
router: Router<S>,
config: RequestLoggingConfig,
include_context: bool,
) -> Router<S>
where
S: Clone + Send + Sync + 'static,
{
let router = if let Some(panic_config) = config.panic_recovery.clone() {
router.layer(CatchPanicLayer::custom(move |payload| {
response_for_panic(payload, &panic_config)
}))
} else {
router
};
let config = Arc::new(config);
if include_context {
router.layer(middleware::from_fn_with_state(
config,
request_logging_middleware::<true>,
))
} else {
router.layer(middleware::from_fn_with_state(
config,
request_logging_middleware::<false>,
))
}
}
async fn request_logging_middleware<const INCLUDE_CONTEXT: bool>(
State(config): State<Arc<RequestLoggingConfig>>,
mut request: Request,
next: Next,
) -> AxumResponse {
let request_log =
INCLUDE_CONTEXT.then(|| RequestLogContext::with_limits(config.limits.clone()));
if let Some(request_log) = &request_log {
request.extensions_mut().insert(request_log.clone());
}
let metadata = RequestLogMetadata::from_request(&mut request, &config, request_log.as_ref());
let started_at = Instant::now();
let mut response = if let Some(request_log) = &request_log {
scope_request_log(request_log.clone(), next.run(request)).await
} else {
next.run(request).await
};
let latency = started_at.elapsed();
log_response(&response, latency, &metadata, request_log.as_ref(), &config);
if config.expose_context_in_response
&& let Some(request_log) = request_log
{
response.extensions_mut().insert(request_log);
}
response.headers_mut().insert(
config.request_id_header.clone(),
metadata.request_id_header_value.clone(),
);
response
}
fn log_response<B>(
response: &Response<B>,
latency: Duration,
metadata: &RequestLogMetadata,
request_log: Option<&RequestLogContext>,
config: &RequestLoggingConfig,
) {
let status = response.status();
let error = response.extensions().get::<ErrorLogMetadata>();
let request_decision = request_log.map(RequestLogContext::decision);
let has_request_failures = request_decision.is_some_and(|decision| decision.has_failures);
let is_error = error.is_some()
|| status.is_client_error()
|| status.is_server_error()
|| has_request_failures;
let is_system_error = error.is_some_and(ErrorLogMetadata::has_internal_diagnostics)
|| (error.is_none() && status.is_server_error())
|| has_request_failures;
let operation_kind = request_decision
.and_then(|decision| decision.operation_kind)
.unwrap_or_else(|| operation_kind_from_method(&metadata.method));
let is_slow = config.is_slow_request(latency);
if config.quiet_queries
&& operation_kind == OperationKind::Query
&& !is_system_error
&& !(is_slow && config.log_slow_queries)
{
return;
}
let bypass_regular_policy = is_slow
|| (is_error && config.always_log_errors)
|| (operation_kind == OperationKind::Command && config.always_log_commands);
let level = if is_system_error {
RequestEventLevel::Error
} else if error.is_some() || status.is_client_error() || is_slow {
RequestEventLevel::Warn
} else {
RequestEventLevel::Info
};
if !level.is_enabled() {
return;
}
if !bypass_regular_policy
&& (config.should_skip_success(metadata) || !config.should_sample_success())
{
return;
}
let handler_latency_ms = latency.as_secs_f64() * 1_000.0;
let event = RequestEvent {
metadata,
include_query: config.include_query,
max_uri_bytes: config.limits.max_uri_bytes,
status,
handler_latency_ms,
is_slow,
operation_kind: match operation_kind {
OperationKind::Query => "query",
OperationKind::Command => "command",
},
outcome: if is_error { "failure" } else { "success" },
request_context: if request_decision.is_some_and(|decision| decision.is_empty) {
None
} else {
request_log
},
};
emit_response_event(&event, error, level);
}
fn operation_kind_from_method(method: &Method) -> OperationKind {
if method == Method::GET || method == Method::HEAD || method == Method::OPTIONS {
OperationKind::Query
} else {
OperationKind::Command
}
}
fn emit_response_event(
event: &RequestEvent<'_>,
error: Option<&ErrorLogMetadata>,
level: RequestEventLevel,
) {
if let Some(error) = error {
match level {
RequestEventLevel::Error => emit_request_event!(
tracing::Level::ERROR,
event;
{ ERROR_FIELD } = %ErrorJson(error),
),
RequestEventLevel::Warn => emit_request_event!(
tracing::Level::WARN,
event;
{ ERROR_FIELD } = %ErrorJson(error),
),
RequestEventLevel::Info => emit_request_event!(
tracing::Level::INFO,
event;
{ ERROR_FIELD } = %ErrorJson(error),
),
}
} else {
match level {
RequestEventLevel::Error => {
emit_request_event!(tracing::Level::ERROR, event;);
}
RequestEventLevel::Warn => {
emit_request_event!(tracing::Level::WARN, event;);
}
RequestEventLevel::Info => {
emit_request_event!(tracing::Level::INFO, event;);
}
}
}
}
fn write_json<T>(formatter: &mut fmt::Formatter<'_>, value: &T) -> fmt::Result
where
T: Serialize + ?Sized,
{
serde_json::to_writer(FormatterWriteAdapter(formatter), value).map_err(|_| fmt::Error)
}
struct FormatterWriteAdapter<'formatter, 'buffer>(&'formatter mut fmt::Formatter<'buffer>);
impl std::io::Write for FormatterWriteAdapter<'_, '_> {
fn write(&mut self, buffer: &[u8]) -> std::io::Result<usize> {
let value = std::str::from_utf8(buffer)
.map_err(|error| std::io::Error::new(std::io::ErrorKind::InvalidData, error))?;
self.0
.write_str(value)
.map_err(|_| std::io::Error::other("写入 JSON 日志字段失败"))?;
Ok(buffer.len())
}
fn flush(&mut self) -> std::io::Result<()> {
Ok(())
}
}
#[cfg(test)]
mod tests {
use std::{
io::{self, Write},
sync::Mutex,
};
use axum::{
Extension,
body::Body,
http::{
Request, StatusCode,
header::{CONTENT_TYPE, USER_AGENT},
},
routing::{get, post},
};
use http_body_util::BodyExt;
use tower::ServiceExt;
use tracing_subscriber::fmt::{MakeWriter, format::JsonFields};
use super::*;
#[derive(Clone, Default)]
struct SharedWriter {
bytes: Arc<Mutex<Vec<u8>>>,
}
struct SharedWriterGuard {
bytes: Arc<Mutex<Vec<u8>>>,
}
impl Write for SharedWriterGuard {
fn write(&mut self, buffer: &[u8]) -> io::Result<usize> {
self.bytes
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.extend_from_slice(buffer);
Ok(buffer.len())
}
fn flush(&mut self) -> io::Result<()> {
Ok(())
}
}
impl<'a> MakeWriter<'a> for SharedWriter {
type Writer = SharedWriterGuard;
fn make_writer(&'a self) -> Self::Writer {
SharedWriterGuard {
bytes: Arc::clone(&self.bytes),
}
}
}
impl SharedWriter {
fn output(&self) -> String {
let bytes = self
.bytes
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.clone();
String::from_utf8(bytes).unwrap()
}
}
fn set_json_subscriber(
writer: &SharedWriter,
max_level: tracing::Level,
) -> tracing::subscriber::DefaultGuard {
let subscriber = tracing_subscriber::fmt()
.fmt_fields(JsonFields::new())
.event_format(super::super::StructuredJsonFormatter::new())
.with_max_level(max_level)
.with_writer(writer.clone())
.finish();
tracing::subscriber::set_default(subscriber)
}
#[test]
fn structured_formatter_preserves_regular_fields_and_current_span() {
let writer = SharedWriter::default();
let _guard = set_json_subscriber(&writer, tracing::Level::TRACE);
let span = tracing::info_span!("业务跨度", user_id = 1001_u64);
span.in_scope(|| {
tracing::info!(count = 2_u64, detail = %"带\"引号", "普通日志");
});
let output = writer.output();
assert_eq!(output.lines().count(), 1);
let log: serde_json::Value = serde_json::from_str(output.trim()).unwrap();
assert_eq!(log["fields"]["message"], "普通日志");
assert_eq!(log["fields"]["count"], 2);
assert_eq!(log["fields"]["detail"], "带\"引号");
assert_eq!(log["span"]["name"], "业务跨度");
assert_eq!(log["span"]["user_id"], 1001);
}
#[test]
fn cloned_context_shares_fields() {
let context = RequestLogContext::new();
let cloned = context.clone();
context.insert("user_id", 1001);
cloned.insert("result", "成功");
let snapshot = context.snapshot();
assert_eq!(snapshot.get("user_id").map(String::as_str), Some("1001"));
assert_eq!(snapshot.get("result").map(String::as_str), Some("成功"));
assert_eq!(cloned.remove("result").as_deref(), Some("成功"));
assert!(!context.snapshot().contains_key("result"));
}
#[test]
fn context_supports_concurrent_writers_without_losing_fields() {
let context = RequestLogContext::with_limits(RequestLoggingLimits::new().max_fields(2_000));
let threads = (0..8)
.map(|thread_id| {
let context = context.clone();
std::thread::spawn(move || {
for field_id in 0..250 {
context.insert(format!("{thread_id}:{field_id}"), field_id);
}
})
})
.collect::<Vec<_>>();
for thread in threads {
thread.join().unwrap();
}
assert_eq!(context.snapshot().len(), 2_000);
}
#[test]
fn config_does_not_duplicate_headers() {
let config = RequestLoggingConfig::default()
.include_header(USER_AGENT)
.include_headers([USER_AGENT, CONTENT_TYPE]);
assert_eq!(config.included_headers.len(), 2);
let config = config.without_headers();
assert!(config.included_headers.is_empty());
}
#[test]
fn default_config_uses_recommended_log_policy() {
let config = RequestLoggingConfig::default();
assert!(config.included_headers.is_empty());
assert_eq!(config.skipped_success_paths, ["/health", "/metrics"]);
assert_eq!(config.skipped_success_prefixes, ["/static/"]);
assert_eq!(
config.slow_request_threshold,
Some(Duration::from_millis(400))
);
assert_eq!(config.success_sample_threshold, SUCCESS_SAMPLE_SCALE);
assert!(config.always_log_errors);
let config = config.without_panic_recovery();
assert!(config.panic_recovery.is_none());
}
#[test]
fn fallible_subject_length_rejects_zero() {
assert!(
RequestLoggingConfig::new()
.try_trusted_subject_max_length(0)
.is_err()
);
}
#[test]
fn partial_success_sampling_is_stable() {
let config = RequestLoggingConfig::new().success_sample_rate(0.25);
let sampled = (0..10_000)
.filter(|_| config.should_sample_success())
.count();
assert!((2_300..=2_700).contains(&sampled));
}
#[test]
#[should_panic(expected = "成功请求日志采样率必须在 0.0 到 1.0 之间")]
fn invalid_success_sample_rate_panics() {
let _ = RequestLoggingConfig::new().success_sample_rate(1.1);
}
#[test]
fn sampling_boundaries_are_exact_and_non_finite_rates_are_rejected() {
let never = RequestLoggingConfig::new().success_sample_rate(0.0);
let always = RequestLoggingConfig::new().success_sample_rate(1.0);
assert!((0..1_000).all(|_| !never.should_sample_success()));
assert!((0..1_000).all(|_| always.should_sample_success()));
assert!(
std::panic::catch_unwind(|| {
RequestLoggingConfig::new().success_sample_rate(f64::NAN)
})
.is_err()
);
assert!(
std::panic::catch_unwind(|| {
RequestLoggingConfig::new().success_sample_rate(f64::INFINITY)
})
.is_err()
);
}
#[tokio::test(flavor = "current_thread")]
async fn one_request_emits_one_json_log() {
async fn handler(Extension(context): Extension<RequestLogContext>) -> &'static str {
context.insert("operation", "测试请求");
"完成"
}
let writer = SharedWriter::default();
let _guard = set_json_subscriber(&writer, tracing::Level::TRACE);
let app = Router::new()
.route("/test", get(handler))
.with_request_logging();
let response = app
.oneshot(Request::get("/test").body(Body::empty()).unwrap())
.await
.unwrap();
assert_eq!(response.status(), axum::http::StatusCode::OK);
let output = writer.output();
assert_eq!(output.lines().count(), 1);
assert!(output.contains("测试请求"));
let log: serde_json::Value = serde_json::from_str(output.trim()).unwrap();
assert!(log.get("span").is_none());
assert_eq!(log["fields"]["method"], "GET");
assert_eq!(log["fields"]["route"], "/test");
assert_eq!(log["fields"]["path"], "/test");
assert_eq!(log["fields"]["uri"], "/test");
let request_id = log["fields"]["request_id"].as_str().unwrap();
assert!(!request_id.is_empty());
assert_eq!(
response
.headers()
.get("x-request-id")
.unwrap()
.to_str()
.unwrap(),
request_id
);
assert_eq!(log["fields"]["request_context"]["operation"], "测试请求");
}
#[tokio::test(flavor = "current_thread")]
async fn access_logging_does_not_create_request_context() {
let writer = SharedWriter::default();
let _guard = set_json_subscriber(&writer, tracing::Level::TRACE);
let app = Router::new()
.route("/test", get(|| async { "完成" }))
.with_access_logging();
let response = app
.oneshot(Request::get("/test").body(Body::empty()).unwrap())
.await
.unwrap();
assert_eq!(response.status(), StatusCode::OK);
assert!(response.extensions().get::<RequestLogContext>().is_none());
let output = writer.output();
assert_eq!(output.lines().count(), 1);
let log: serde_json::Value = serde_json::from_str(output.trim()).unwrap();
assert!(log["fields"].get("request_context").is_none());
}
#[tokio::test(flavor = "current_thread")]
async fn complete_context_is_exposed_in_response_only_when_enabled() {
for (expose, expected) in [(false, false), (true, true)] {
let config = RequestLoggingConfig::new()
.success_sample_rate(0.0)
.expose_context_in_response(expose);
let app = Router::new()
.route("/test", get(|| async { "完成" }))
.with_request_logging_config(config);
let response = app
.oneshot(Request::get("/test").body(Body::empty()).unwrap())
.await
.unwrap();
assert_eq!(
response.extensions().get::<RequestLogContext>().is_some(),
expected
);
}
}
#[tokio::test(flavor = "current_thread")]
async fn slow_queries_can_be_logged_independently_from_quiet_queries() {
async fn run(log_slow: bool) -> String {
let writer = SharedWriter::default();
let _guard = set_json_subscriber(&writer, tracing::Level::TRACE);
let config = RequestLoggingConfig::new()
.quiet_queries(true)
.log_slow_queries(log_slow)
.slow_request_threshold(Duration::ZERO);
let app = Router::new()
.route("/query", get(|| async { "完成" }))
.with_request_logging_config(config);
app.oneshot(Request::get("/query").body(Body::empty()).unwrap())
.await
.unwrap();
writer.output()
}
assert!(run(false).await.is_empty());
assert_eq!(run(true).await.lines().count(), 1);
}
#[tokio::test(flavor = "current_thread")]
async fn subscriber_level_filter_skips_disabled_success_event() {
async fn error_handler() -> Result<&'static str, crate::web::response::ApiError> {
Err(crate::web::response::ApiError::err_bad_request("请求错误"))
}
let writer = SharedWriter::default();
let _guard = set_json_subscriber(&writer, tracing::Level::WARN);
let app = Router::new()
.route("/success", get(|| async { "完成" }))
.route("/error", get(error_handler))
.with_request_logging();
for uri in ["/success", "/error"] {
let response = app
.clone()
.oneshot(Request::get(uri).body(Body::empty()).unwrap())
.await
.unwrap();
assert_eq!(response.status(), StatusCode::OK);
}
let output = writer.output();
assert_eq!(output.lines().count(), 1);
assert!(output.contains(r#""level":"WARN""#));
assert!(output.contains(r#""path":"/error""#));
}
#[tokio::test(flavor = "current_thread")]
async fn request_headers_are_not_recorded_by_default() {
let writer = SharedWriter::default();
let _guard = set_json_subscriber(&writer, tracing::Level::TRACE);
let app = Router::new()
.route("/test", get(|| async { "完成" }))
.with_request_logging();
let response = app
.oneshot(
Request::get("/test")
.header(USER_AGENT, "loveyu-kit-test-client")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(response.status(), StatusCode::OK);
let output = writer.output();
assert!(!output.contains("loveyu-kit-test-client"));
assert!(!output.contains(r#""headers""#));
}
#[tokio::test(flavor = "current_thread")]
async fn configured_request_headers_are_recorded() {
let writer = SharedWriter::default();
let _guard = set_json_subscriber(&writer, tracing::Level::TRACE);
let config = RequestLoggingConfig::new().include_headers([USER_AGENT, CONTENT_TYPE]);
let app = Router::new()
.route("/test", get(|| async { "完成" }))
.with_request_logging_config(config);
let response = app
.oneshot(
Request::get("/test")
.header(USER_AGENT, "loveyu-kit-test-client")
.header(CONTENT_TYPE, "application/json")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(response.status(), StatusCode::OK);
let output = writer.output();
let log: serde_json::Value = serde_json::from_str(output.trim()).unwrap();
assert_eq!(
log["fields"]["headers"]["user-agent"],
"loveyu-kit-test-client"
);
assert_eq!(log["fields"]["headers"]["content-type"], "application/json");
}
#[tokio::test(flavor = "current_thread")]
async fn query_string_is_recorded_only_when_enabled() {
async fn request(include_query: bool) -> String {
let writer = SharedWriter::default();
let _guard = set_json_subscriber(&writer, tracing::Level::TRACE);
let config = RequestLoggingConfig::new().include_query(include_query);
let app = Router::new()
.route("/test", get(|| async { "完成" }))
.with_request_logging_config(config);
let response = app
.oneshot(
Request::get("/test?debug=loveyu-kit-query")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(response.status(), StatusCode::OK);
writer.output()
}
assert!(!request(false).await.contains("loveyu-kit-query"));
assert!(request(true).await.contains("loveyu-kit-query"));
}
#[tokio::test(flavor = "current_thread")]
async fn skipped_success_paths_and_prefixes_do_not_emit_logs() {
async fn handler() -> &'static str {
"完成"
}
let writer = SharedWriter::default();
let _guard = set_json_subscriber(&writer, tracing::Level::TRACE);
let config = RequestLoggingConfig::new()
.skip_success_path("/health")
.skip_success_path("/users/{id}")
.skip_success_prefix("/static/");
let app = Router::new()
.route("/health", get(handler))
.route("/users/{id}", get(handler))
.route("/static/app.js", get(handler))
.route("/normal", get(handler))
.with_request_logging_config(config);
for uri in ["/health", "/users/1", "/static/app.js", "/normal"] {
let response = app
.clone()
.oneshot(Request::get(uri).body(Body::empty()).unwrap())
.await
.unwrap();
assert_eq!(response.status(), StatusCode::OK);
}
let output = writer.output();
assert_eq!(output.lines().count(), 1);
assert!(output.contains(r#""path":"/normal""#));
}
#[tokio::test(flavor = "current_thread")]
async fn zero_success_sample_rate_skips_success_log() {
let writer = SharedWriter::default();
let _guard = set_json_subscriber(&writer, tracing::Level::TRACE);
let config = RequestLoggingConfig::new().success_sample_rate(0.0);
let app = Router::new()
.route("/test", get(|| async { "完成" }))
.with_request_logging_config(config);
let response = app
.oneshot(Request::get("/test").body(Body::empty()).unwrap())
.await
.unwrap();
assert_eq!(response.status(), StatusCode::OK);
assert!(writer.output().is_empty());
}
#[tokio::test(flavor = "current_thread")]
async fn slow_request_overrides_success_path_filter() {
let writer = SharedWriter::default();
let _guard = set_json_subscriber(&writer, tracing::Level::TRACE);
let config = RequestLoggingConfig::new()
.skip_success_path("/health")
.slow_request_threshold(Duration::ZERO);
let app = Router::new()
.route("/health", get(|| async { "正常" }))
.with_request_logging_config(config);
let response = app
.oneshot(Request::get("/health").body(Body::empty()).unwrap())
.await
.unwrap();
assert_eq!(response.status(), StatusCode::OK);
let output = writer.output();
assert_eq!(output.lines().count(), 1);
assert!(output.contains(r#""level":"WARN""#));
assert!(output.contains(r#""slow_request":true"#));
}
#[tokio::test(flavor = "current_thread")]
async fn errors_are_logged_even_when_success_logs_are_disabled() {
async fn handler() -> Result<&'static str, crate::web::response::ApiError> {
Err(crate::web::response::ApiError::err_not_found("数据不存在"))
}
let writer = SharedWriter::default();
let _guard = set_json_subscriber(&writer, tracing::Level::TRACE);
let config = RequestLoggingConfig::new()
.skip_success_path("/error")
.success_sample_rate(0.0)
.always_log_errors(true);
let app = Router::new()
.route("/error", get(handler))
.with_request_logging_config(config);
let response = app
.oneshot(Request::get("/error").body(Body::empty()).unwrap())
.await
.unwrap();
assert_eq!(response.status(), StatusCode::OK);
let output = writer.output();
assert_eq!(output.lines().count(), 1);
assert!(output.contains(r#""error":{"code":404000"#));
}
#[tokio::test(flavor = "current_thread")]
async fn errors_can_follow_filter_and_sampling_rules() {
async fn handler() -> Result<&'static str, crate::web::response::ApiError> {
Err(crate::web::response::ApiError::err_not_found("数据不存在"))
}
let writer = SharedWriter::default();
let _guard = set_json_subscriber(&writer, tracing::Level::TRACE);
let config = RequestLoggingConfig::new()
.skip_success_path("/error")
.success_sample_rate(0.0)
.always_log_errors(false);
let app = Router::new()
.route("/error", get(handler))
.with_request_logging_config(config);
let response = app
.oneshot(Request::get("/error").body(Body::empty()).unwrap())
.await
.unwrap();
assert_eq!(response.status(), StatusCode::OK);
assert!(writer.output().is_empty());
}
#[tokio::test(flavor = "current_thread")]
async fn panic_returns_safe_response_and_logs_real_error_once() {
async fn handler(Extension(context): Extension<RequestLogContext>) -> &'static str {
context.insert("operation", "panic 前的业务操作");
panic!("测试 panic 详情");
}
let writer = SharedWriter::default();
let _guard = set_json_subscriber(&writer, tracing::Level::TRACE);
let app = Router::new()
.route("/panic", get(handler))
.with_request_logging();
let response = app
.oneshot(Request::get("/panic").body(Body::empty()).unwrap())
.await
.unwrap();
assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);
let body = response.into_body().collect().await.unwrap().to_bytes();
let value: serde_json::Value = serde_json::from_slice(&body).unwrap();
assert_eq!(value["code"], 500_000);
assert_eq!(value["msg"], "系统内部错误");
assert!(!String::from_utf8_lossy(&body).contains("测试 panic 详情"));
let output = writer.output();
assert_eq!(output.lines().count(), 1);
let log: serde_json::Value = serde_json::from_str(output.trim()).unwrap();
assert_eq!(log["level"], "ERROR");
assert_eq!(log["fields"]["error"]["internal_error"], "测试 panic 详情");
assert_eq!(log["fields"]["error"]["context"]["error_type"], "panic");
assert_eq!(
log["fields"]["request_context"]["operation"],
"panic 前的业务操作"
);
}
#[tokio::test(flavor = "current_thread")]
async fn system_error_logs_internal_details_without_exposing_them() {
async fn handler() -> Result<&'static str, crate::web::response::ApiError> {
Err(crate::web::response::ApiError::err_database("查询失败")
.with_error("数据库连接被拒绝")
.with_context("operation", "查询用户"))
}
let writer = SharedWriter::default();
let _guard = set_json_subscriber(&writer, tracing::Level::TRACE);
let app = Router::new()
.route("/error", get(handler))
.with_request_logging();
let response = app
.oneshot(Request::get("/error").body(Body::empty()).unwrap())
.await
.unwrap();
let body = response.into_body().collect().await.unwrap().to_bytes();
assert!(!String::from_utf8_lossy(&body).contains("数据库连接被拒绝"));
let output = writer.output();
assert_eq!(output.lines().count(), 1);
let log: serde_json::Value = serde_json::from_str(output.trim()).unwrap();
assert_eq!(log["level"], "ERROR");
assert_eq!(log["fields"]["error"]["internal_error"], "数据库连接被拒绝");
assert_eq!(log["fields"]["error"]["context"]["operation"], "查询用户");
}
#[tokio::test(flavor = "current_thread")]
async fn diagnostic_context_is_logged_without_internal_error() {
async fn handler() -> Result<&'static str, crate::web::response::ApiError> {
Err(crate::web::response::ApiError::err_bad_request("请求错误")
.with_context("operation", "解析请求"))
}
let writer = SharedWriter::default();
let _guard = set_json_subscriber(&writer, tracing::Level::TRACE);
let app = Router::new()
.route("/error", get(handler))
.with_request_logging();
let response = app
.oneshot(Request::get("/error").body(Body::empty()).unwrap())
.await
.unwrap();
assert_eq!(response.status(), StatusCode::OK);
let output = writer.output();
assert_eq!(output.lines().count(), 1);
let log: serde_json::Value = serde_json::from_str(output.trim()).unwrap();
assert_eq!(log["level"], "WARN");
assert_eq!(log["fields"]["error"]["context"]["operation"], "解析请求");
}
#[tokio::test(flavor = "current_thread")]
async fn trusted_subject_and_request_id_are_propagated_generically() {
async fn handler(subject: TrustedSubject, request_id: RequestId) -> String {
format!("{}:{request_id}", subject.id())
}
let writer = SharedWriter::default();
let _guard = set_json_subscriber(&writer, tracing::Level::TRACE);
let subject_header = HeaderName::from_static("x-gateway-subject");
let config = RequestLoggingConfig::new()
.trusted_subject_header(subject_header.clone())
.trusted_subject_kind("user");
let app = Router::new()
.route("/profile", get(handler))
.with_request_logging_config(config);
let response = app
.oneshot(
Request::get("/profile")
.header(subject_header, "guid-1001")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(response.status(), StatusCode::OK);
let log: serde_json::Value = serde_json::from_str(writer.output().trim()).unwrap();
assert_eq!(
log["fields"]["request_context"]["subject"]["id"],
"guid-1001"
);
assert_eq!(log["fields"]["request_context"]["subject"]["kind"], "user");
}
#[tokio::test(flavor = "current_thread")]
async fn quiet_queries_and_always_logged_commands_are_configurable() {
let writer = SharedWriter::default();
let _guard = set_json_subscriber(&writer, tracing::Level::TRACE);
let config = RequestLoggingConfig::new()
.quiet_queries(true)
.always_log_commands(true)
.success_sample_rate(0.0);
let app = Router::new()
.route("/query", get(|| async { "查询完成" }))
.route("/command", post(|| async { "修改完成" }))
.with_request_logging_config(config);
for request in [
Request::get("/query").body(Body::empty()).unwrap(),
Request::post("/command").body(Body::empty()).unwrap(),
] {
assert_eq!(
app.clone().oneshot(request).await.unwrap().status(),
StatusCode::OK
);
}
let output = writer.output();
assert_eq!(output.lines().count(), 1);
let log: serde_json::Value = serde_json::from_str(output.trim()).unwrap();
assert_eq!(log["fields"]["path"], "/command");
assert_eq!(log["fields"]["operation_kind"], "command");
}
#[tokio::test(flavor = "current_thread")]
async fn sql_failure_is_aggregated_into_the_single_request_json() {
use std::{error::Error, fmt};
use crate::observability::{ResultApiErrorExt, SqlDiagnostic, SqlOperation};
#[derive(Debug)]
struct DatabaseError;
impl fmt::Display for DatabaseError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str("唯一索引冲突")
}
}
impl Error for DatabaseError {}
async fn handler() -> Result<&'static str, crate::web::response::ApiError> {
let result: Result<(), DatabaseError> = Err(DatabaseError);
result.map_sql_error(
crate::web::response::ApiError::err_database("保存失败,请稍后重试"),
|source| {
SqlDiagnostic::new(
"create_user",
SqlOperation::Insert,
"INSERT INTO users(email) VALUES (?)",
source,
)
.with_safe_parameter("user_guid", "guid-1001")
.with_error_code("1062")
.with_constraint("uk_users_email")
},
)?;
Ok("不会执行")
}
let writer = SharedWriter::default();
let _guard = set_json_subscriber(&writer, tracing::Level::TRACE);
let app = Router::new()
.route("/users", post(handler))
.with_request_logging();
let response = app
.oneshot(Request::post("/users").body(Body::empty()).unwrap())
.await
.unwrap();
assert_eq!(response.status(), StatusCode::OK);
let body = response.into_body().collect().await.unwrap().to_bytes();
assert!(!String::from_utf8_lossy(&body).contains("唯一索引冲突"));
assert!(!String::from_utf8_lossy(&body).contains("uk_users_email"));
let output = writer.output();
assert_eq!(output.lines().count(), 1);
let log: serde_json::Value = serde_json::from_str(output.trim()).unwrap();
let diagnostic = &log["fields"]["error"]["diagnostics"][0];
assert_eq!(diagnostic["kind"], "sql");
assert_eq!(diagnostic["name"], "create_user");
assert_eq!(diagnostic["error"], "唯一索引冲突");
assert_eq!(diagnostic["details"]["operation"], "insert");
assert_eq!(diagnostic["details"]["error_code"], "1062");
assert_eq!(
diagnostic["details"]["safe_parameters"]["user_guid"],
"guid-1001"
);
}
#[tokio::test(flavor = "current_thread")]
async fn recovered_sql_failure_is_not_hidden_by_quiet_query_policy() {
use crate::observability::{SqlDiagnostic, SqlOperation};
async fn handler() -> &'static str {
RequestLogContext::with_current(|context| {
context.record_sql_error(SqlDiagnostic::new(
"load_settings",
SqlOperation::Select,
"SELECT value FROM settings WHERE name = ?",
"数据库连接超时",
));
});
"使用默认配置"
}
let writer = SharedWriter::default();
let _guard = set_json_subscriber(&writer, tracing::Level::TRACE);
let config = RequestLoggingConfig::new()
.quiet_queries(true)
.success_sample_rate(0.0);
let app = Router::new()
.route("/settings", get(handler))
.with_request_logging_config(config);
let response = app
.oneshot(Request::get("/settings").body(Body::empty()).unwrap())
.await
.unwrap();
assert_eq!(response.status(), StatusCode::OK);
let output = writer.output();
assert_eq!(output.lines().count(), 1);
let log: serde_json::Value = serde_json::from_str(output.trim()).unwrap();
assert_eq!(log["level"], "ERROR");
assert_eq!(log["fields"]["outcome"], "failure");
assert_eq!(
log["fields"]["request_context"]["diagnostics"][0]["name"],
"load_settings"
);
}
#[tokio::test(flavor = "current_thread")]
async fn sensitive_headers_remain_redacted_when_included() {
use axum::http::header::AUTHORIZATION;
let writer = SharedWriter::default();
let _guard = set_json_subscriber(&writer, tracing::Level::TRACE);
let config = RequestLoggingConfig::new().include_header(AUTHORIZATION);
let app = Router::new()
.route("/test", get(|| async { "完成" }))
.with_request_logging_config(config);
let response = app
.oneshot(
Request::get("/test")
.header(AUTHORIZATION, "Bearer secret-token")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(response.status(), StatusCode::OK);
let output = writer.output();
assert!(!output.contains("secret-token"));
let log: serde_json::Value = serde_json::from_str(output.trim()).unwrap();
assert_eq!(log["fields"]["headers"]["authorization"], "[已脱敏]");
}
}