Skip to main content

structured_logging/
lib.rs

1//! # Enhanced Structured Logging for SpinKube Agents
2//!
3//! This crate provides performance optimizations and convenience APIs on top of the excellent
4//! `observability_core` hexagonal architecture. It focuses on:
5//!
6//! - 🚀 **Performance**: String interning, buffer pooling, zero-allocation fast paths
7//! - 🔗 **Correlation**: Enhanced W3C baggage, scoped contexts, advanced tracing
8//! - 🎪 **Convenience**: Domain-specific APIs for LLM, template, and A2A operations
9//!
10//! ## Architecture
11//!
12//! This crate builds on `observability_core`'s solid foundation:
13//! - **Domain**: Reuses LogEntry, ProcessorChain, TraceContext
14//! - **Ports**: Extends TransportPort, FormatterPort interfaces  
15//! - **Adapters**: Enhances with performance-optimized implementations
16//! - **Extension**: Provides enhanced configuration and management
17//!
18//! ## Usage Tiers
19//!
20//! ### Tier 1: Standard (90% of users)
21//! ```rust,ignore
22//! // Just use observability_core - works perfectly
23//! use observability_core::ObservabilityManager;
24//! log::info!("Standard structured logging");
25//! ```
26//!
27//! ### Tier 2: Enhanced (8% of users)  
28//! ```rust,ignore
29//! // Add convenience methods
30//! use structured_logging::convenience::*;
31//! log_llm_request("gpt-4", duration, tokens, "success")?;
32//! ```
33//!
34//! ### Tier 3: Performance (2% of users)
35//! ```rust,ignore
36//! // Full performance optimization
37//! use structured_logging::{EnhancedObservabilityConfig, PerformanceExtension};
38//! ```
39
40// 🚀 PERFORMANCE ENHANCEMENTS
41#[cfg(feature = "performance-optimized")]
42pub mod performance;
43
44// 🔗 CORRELATION ENHANCEMENTS
45#[cfg(feature = "correlation-enhanced")]
46pub mod correlation;
47
48// 🎪 CONVENIENCE APIs
49#[cfg(feature = "convenience")]
50pub mod convenience;
51
52// 🔌 CONTEXT ADAPTER for observability_core integration
53#[cfg(feature = "convenience")]
54pub mod context_adapter;
55
56// 🛡️ PANIC HANDLING
57pub mod panic_handler;
58
59// 🧩 ENHANCED CONFIGURATION AND MANAGEMENT
60pub mod extension;
61
62// Error types
63mod error;
64
65// 🏛️ RE-EXPORT FOUNDATION - Use observability_core as the source of truth
66pub use observability_core::{
67    BatchingConfig,
68    BatchingManager,
69    CompactJsonFormatter,
70    ContextPort,
71    FormatterPort,
72    JsonFormatter,
73    // Core domain types
74    LogEntry,
75    ObservabilityConfig,
76
77    // Error handling
78    ObservabilityError,
79    // Core framework
80    ObservabilityManager,
81    ObservabilityResult,
82
83    ProcessorChain,
84    StandardLogAdapter,
85
86    StandardLoggingPort,
87    // Ports and adapters
88    TransportPort,
89    // Utilities
90    W3CTraceContext,
91    WasmStdoutAdapter,
92    traits::LogLevel,
93};
94
95// Re-export the correct TraceContext from domain
96pub use observability_core::domain::TraceContext;
97
98// 🎯 ENHANCED FUNCTIONALITY
99pub use error::{Result, StructuredLoggingError};
100pub use extension::{
101    EnhancedObservabilityConfig, PerformanceExtension, create_performance_extension,
102    create_performance_extension_from_config,
103};
104
105// 🛡️ PANIC HANDLING EXPORTS
106pub use panic_handler::{
107    PanicHandlerConfig, PanicPattern, PanicSeverity, PanicStats, StructuredPanicInfo, ThreadInfo,
108    get_panic_stats, install_panic_handler, install_panic_handler_with_config, reset_panic_stats,
109};
110
111// 🛡️ The `supervised` macro is available at crate root due to #[macro_export]
112// No need to re-export it - it's automatically available as structured_logging::supervised!
113
114// 🚀 PERFORMANCE EXPORTS (feature-gated)
115#[cfg(feature = "performance-optimized")]
116pub use performance::{
117    BufferPool, FastPathLogger, OptimizedWasmStdoutAdapter, PerformanceStats,
118    StringInterningProcessor,
119};
120
121// 🔗 CORRELATION EXPORTS (feature-gated)
122#[cfg(feature = "correlation-enhanced")]
123pub use correlation::{
124    BaggageManager, CorrelationProcessor, EnhancedTraceContext, ScopedContextManager,
125    W3CBaggageSupport,
126};
127
128// 🎪 CONVENIENCE EXPORTS (feature-gated)
129#[cfg(feature = "convenience")]
130pub use convenience::{
131    A2AContext,
132    ConvenienceManager,
133    // Processors
134    DomainContextProcessor,
135    // Context types
136    LLMContext,
137    TemplateContext,
138    clear_a2a_context,
139    clear_all_contexts,
140    clear_llm_context,
141    clear_request_context,
142    clear_template_context,
143    emit_a2a_message_latency,
144    emit_counter,
145    emit_histogram,
146    // Metrics convenience functions
147    emit_llm_request_duration,
148    emit_llm_tokens_used,
149    emit_request_duration,
150    emit_template_render_duration,
151    log_a2a_message,
152    // Convenience logging functions
153    log_llm_request,
154    log_template_render,
155    set_a2a_context,
156    // Context management
157    set_llm_context,
158    set_request_context,
159    set_template_context,
160};
161
162// 🔌 ADVANCED CONTEXT MANAGEMENT EXPORTS (feature-gated)
163#[cfg(feature = "convenience")]
164pub use context_adapter::{
165    A2aContextGuard,
166    A2aContextManager,
167    AllContextsGuard,
168
169    ContextManagerRegistry,
170    // RAII guards
171    LlmContextGuard,
172    // Traits (for advanced users)
173    LlmContextManager,
174    RequestContextGuard,
175    RequestContextManager,
176    // Advanced builder
177    ScopedContextBuilder,
178
179    StructuredA2aContextManager,
180    // Registry and managers
181    StructuredContextRegistry,
182    StructuredLlmContextManager,
183    StructuredRequestContextManager,
184    // Initialization
185    init_context_integration,
186
187    set_a2a_context_scoped,
188    set_all_contexts_scoped,
189
190    // Scoped context setting
191    set_llm_context_scoped,
192    set_request_context_scoped,
193    with_a2a_context,
194    with_all_contexts,
195
196    // Scoped callbacks
197    with_llm_context,
198    with_request_context,
199};
200
201// Re-export configuration types
202#[cfg(feature = "convenience")]
203pub use extension::ConvenienceConfig;
204#[cfg(feature = "correlation-enhanced")]
205pub use extension::CorrelationConfig;
206#[cfg(feature = "performance-optimized")]
207pub use extension::PerformanceConfig;
208
209/// Version information
210pub const VERSION: &str = env!("CARGO_PKG_VERSION");
211
212/// Create a logger using observability_core foundation
213pub fn create_logger() -> ObservabilityResult<ObservabilityManager> {
214    ObservabilityManager::new(ObservabilityConfig::default())
215}
216
217/// Create an enhanced logger with performance optimizations
218#[cfg(feature = "performance-optimized")]
219pub fn create_performance_logger() -> Result<PerformanceExtension> {
220    PerformanceExtension::new(EnhancedObservabilityConfig::default())
221}
222
223/// Create logger from configuration
224pub fn create_logger_from_config(
225    config: ObservabilityConfig,
226) -> ObservabilityResult<ObservabilityManager> {
227    ObservabilityManager::new(config)
228}
229
230/// Create enhanced logger from enhanced configuration
231pub fn create_enhanced_logger_from_config(
232    config: EnhancedObservabilityConfig,
233) -> Result<PerformanceExtension> {
234    PerformanceExtension::new(config)
235}
236
237#[cfg(test)]
238mod tests {
239    use super::*;
240
241    #[test]
242    fn test_basic_logger_creation() {
243        let logger = create_logger();
244        assert!(logger.is_ok());
245    }
246
247    #[cfg(feature = "performance-optimized")]
248    #[test]
249    fn test_performance_logger_creation() {
250        let logger = create_performance_logger();
251        assert!(logger.is_ok());
252    }
253
254    #[test]
255    fn test_version_constant() {
256        assert!(!VERSION.is_empty());
257    }
258}