anycms-core 0.5.4

A unified API response library supporting multiple Rust web frameworks
Documentation
//! Tracing integration for anycms-core.
//!
//! Enabled by the `tracing` feature flag.
//!
//! Provides automatic error/warning logging for API responses.
//!
//! # Usage
//!
//! ```ignore
//! use anycms_core::ApiResult;
//! use anycms_core::ApiResultTracing;
//!
//! // Log error response at appropriate level
//! let result: ApiResult<()> = ApiResult::fail("something went wrong")
//!     .with_code(500)
//!     .with_tracing(); // logs at ERROR level
//! ```
//!
//! - Success responses: **no log** (avoid noise)
//! - 4xx error responses: **WARN** level
//! - 5xx error responses: **ERROR** level

#[cfg(feature = "tracing")]
use crate::result::ApiResult;

/// Extension trait for tracing-enabled API responses.
#[cfg(feature = "tracing")]
pub trait ApiResultTracing<T> {
    /// Log this response at the appropriate tracing level and return self.
    ///
    /// - Success responses: no log emitted
    /// - Client errors (4xx): `tracing::warn!`
    /// - Server errors (5xx): `tracing::error!`
    fn with_tracing(self) -> Self;
}

#[cfg(feature = "tracing")]
impl<T> ApiResultTracing<T> for ApiResult<T> {
    fn with_tracing(self) -> Self {
        if !self.success {
            let code = self.code.unwrap_or(0);
            let message = self.message.as_deref().unwrap_or("Unknown error");
            let trace = self.trace_id.as_deref().unwrap_or("-");

            if code >= 500 {
                tracing::error!(
                    code = code,
                    trace_id = trace,
                    biz_code = ?self.biz_code,
                    "API error: {}",
                    message
                );
            } else {
                tracing::warn!(
                    code = code,
                    trace_id = trace,
                    biz_code = ?self.biz_code,
                    "API error: {}",
                    message
                );
            }
        }
        self
    }
}