Skip to main content

structured_logging/
extension.rs

1//! Enhanced configuration and management for structured logging
2//!
3//! This module provides core configuration and management functionality for structured logging
4//! without external extension system dependencies.
5
6use crate::error::{Result, StructuredLoggingError};
7use observability_core::{LogEntry, ObservabilityConfig, ObservabilityManager};
8use serde::{Deserialize, Serialize};
9
10/// Enhanced configuration for structured logging with performance and convenience features
11#[derive(Debug, Clone, Serialize, Deserialize, Default)]
12pub struct EnhancedObservabilityConfig {
13    /// Base observability configuration
14    pub base: ObservabilityConfig,
15
16    /// Performance optimization settings
17    #[cfg(feature = "performance-optimized")]
18    pub performance: PerformanceConfig,
19
20    /// Correlation enhancement settings
21    #[cfg(feature = "correlation-enhanced")]
22    pub correlation: CorrelationConfig,
23
24    /// Convenience feature settings
25    #[cfg(feature = "convenience")]
26    pub convenience: ConvenienceConfig,
27
28    /// Panic handling configuration
29    pub panic_handler: crate::panic_handler::PanicHandlerConfig,
30}
31
32/// Performance optimization configuration
33#[cfg(feature = "performance-optimized")]
34#[derive(Debug, Clone, Serialize, Deserialize)]
35pub struct PerformanceConfig {
36    /// Enable string interning for common log field values
37    pub enable_string_interning: bool,
38
39    /// Initial capacity for string interner
40    pub string_interner_capacity: usize,
41
42    /// Enable buffer pooling for log formatting
43    pub enable_buffer_pooling: bool,
44
45    /// Initial buffer pool size
46    pub buffer_pool_size: usize,
47
48    /// Individual buffer capacity in bytes
49    pub buffer_capacity: usize,
50
51    /// Enable zero-allocation fast paths for hot operations
52    pub enable_fast_paths: bool,
53
54    /// Enable WASM-specific memory optimizations
55    pub enable_wasm_optimizations: bool,
56}
57
58#[cfg(feature = "performance-optimized")]
59impl Default for PerformanceConfig {
60    fn default() -> Self {
61        Self {
62            enable_string_interning: true,
63            string_interner_capacity: 1024,
64            enable_buffer_pooling: true,
65            buffer_pool_size: 16,
66            buffer_capacity: 2048,
67            enable_fast_paths: true,
68            enable_wasm_optimizations: cfg!(target_arch = "wasm32"),
69        }
70    }
71}
72
73/// Correlation enhancement configuration
74#[cfg(feature = "correlation-enhanced")]
75#[derive(Debug, Clone, Serialize, Deserialize)]
76pub struct CorrelationConfig {
77    /// Enable W3C baggage support
78    pub enable_baggage: bool,
79
80    /// Maximum baggage size in bytes
81    pub max_baggage_size: usize,
82
83    /// Enable scoped context management
84    pub enable_scoped_context: bool,
85
86    /// Maximum context nesting depth
87    pub max_context_depth: usize,
88
89    /// Enable automatic context propagation
90    pub enable_auto_propagation: bool,
91}
92
93#[cfg(feature = "correlation-enhanced")]
94impl Default for CorrelationConfig {
95    fn default() -> Self {
96        Self {
97            enable_baggage: true,
98            max_baggage_size: 8192,
99            enable_scoped_context: true,
100            max_context_depth: 16,
101            enable_auto_propagation: true,
102        }
103    }
104}
105
106/// Convenience feature configuration
107#[cfg(feature = "convenience")]
108#[derive(Debug, Clone, Serialize, Deserialize)]
109pub struct ConvenienceConfig {
110    /// Enable LLM operation logging
111    pub enable_llm_logging: bool,
112
113    /// Enable template rendering logging
114    pub enable_template_logging: bool,
115
116    /// Enable A2A message logging
117    pub enable_a2a_logging: bool,
118
119    /// Enable convenience macros
120    pub enable_convenience_macros: bool,
121
122    /// Enable domain-specific field extraction
123    pub enable_domain_fields: bool,
124}
125
126#[cfg(feature = "convenience")]
127impl Default for ConvenienceConfig {
128    fn default() -> Self {
129        Self {
130            enable_llm_logging: true,
131            enable_template_logging: true,
132            enable_a2a_logging: true,
133            enable_convenience_macros: true,
134            enable_domain_fields: true,
135        }
136    }
137}
138
139impl EnhancedObservabilityConfig {
140    /// Create enhanced config with specified base config
141    pub fn with_base(base: ObservabilityConfig) -> Self {
142        Self {
143            base,
144            ..Default::default()
145        }
146    }
147
148    /// Set panic handler configuration  
149    pub fn with_panic_handler(mut self, config: crate::panic_handler::PanicHandlerConfig) -> Self {
150        self.panic_handler = config;
151        self
152    }
153
154    /// Enable all performance features (feature-gated)
155    #[cfg(feature = "performance-optimized")]
156    pub fn with_all_performance_features(mut self) -> Self {
157        self.performance.enable_string_interning = true;
158        self.performance.enable_buffer_pooling = true;
159        self.performance.enable_fast_paths = true;
160        self.performance.enable_wasm_optimizations = true;
161        self
162    }
163
164    /// Disable all performance features (feature-gated)
165    #[cfg(feature = "performance-optimized")]
166    pub fn with_no_performance_features(mut self) -> Self {
167        self.performance = PerformanceConfig::default();
168        self
169    }
170
171    /// Convert to base observability config
172    pub fn to_base_config(&self) -> ObservabilityConfig {
173        self.base.clone()
174    }
175
176    /// Validate configuration
177    pub fn validate(&self) -> Result<()> {
178        // Additional validation for enhanced features
179        #[cfg(feature = "performance-optimized")]
180        {
181            if self.performance.buffer_pool_size == 0 {
182                return Err(StructuredLoggingError::enhanced_config(
183                    "Buffer pool size must be greater than 0",
184                ));
185            }
186
187            if self.performance.buffer_capacity == 0 {
188                return Err(StructuredLoggingError::enhanced_config(
189                    "Buffer capacity must be greater than 0",
190                ));
191            }
192        }
193
194        Ok(())
195    }
196
197    /// Serialize configuration to JSON
198    pub fn to_json(&self) -> Result<String> {
199        serde_json::to_string_pretty(self).map_err(|e| {
200            StructuredLoggingError::enhanced_config(format!("Failed to serialize config: {}", e))
201        })
202    }
203
204    /// Deserialize configuration from JSON
205    pub fn from_json(json: &str) -> Result<Self> {
206        serde_json::from_str(json).map_err(|e| {
207            StructuredLoggingError::enhanced_config(format!("Failed to deserialize config: {}", e))
208        })
209    }
210}
211
212/// Enhanced observability manager with performance and convenience features
213pub struct PerformanceExtension {
214    /// Base observability manager
215    base: ObservabilityManager,
216
217    /// Enhanced configuration
218    config: EnhancedObservabilityConfig,
219
220    /// Performance features
221    #[cfg(feature = "performance-optimized")]
222    performance: Option<crate::performance::PerformanceManager>,
223
224    /// Correlation features
225    #[cfg(feature = "correlation-enhanced")]
226    correlation: Option<crate::correlation::CorrelationManager>,
227
228    /// Convenience features
229    #[cfg(feature = "convenience")]
230    convenience: Option<crate::convenience::ConvenienceManager>,
231}
232
233impl PerformanceExtension {
234    /// Create new enhanced extension
235    pub fn new(config: EnhancedObservabilityConfig) -> Result<Self> {
236        let base =
237            ObservabilityManager::new(config.base.clone()).map_err(StructuredLoggingError::from)?;
238
239        let mut extension = Self {
240            base,
241            config: config.clone(),
242
243            #[cfg(feature = "performance-optimized")]
244            performance: None,
245
246            #[cfg(feature = "correlation-enhanced")]
247            correlation: None,
248
249            #[cfg(feature = "convenience")]
250            convenience: None,
251        };
252
253        // Initialize optional feature modules
254        extension.initialize_features()?;
255
256        Ok(extension)
257    }
258
259    /// Initialize all configured features
260    pub fn initialize(&mut self) -> Result<()> {
261        self.base
262            .initialize()
263            .map_err(StructuredLoggingError::from)?;
264        self.initialize_features()?;
265        Ok(())
266    }
267
268    /// Initialize feature modules based on configuration
269    fn initialize_features(&mut self) -> Result<()> {
270        #[cfg(feature = "performance-optimized")]
271        {
272            if self.is_performance_enabled() {
273                let manager =
274                    crate::performance::PerformanceManager::new(&self.config.performance)?;
275                self.performance = Some(manager);
276            }
277        }
278
279        #[cfg(feature = "correlation-enhanced")]
280        {
281            if self.is_correlation_enabled() {
282                let manager =
283                    crate::correlation::CorrelationManager::new(&self.config.correlation)?;
284                self.correlation = Some(manager);
285            }
286        }
287
288        #[cfg(feature = "convenience")]
289        {
290            if self.is_convenience_enabled() {
291                let manager = crate::convenience::ConvenienceManager::new()?;
292                self.convenience = Some(manager);
293            }
294        }
295
296        // Install panic handler if configured (idempotent — silently succeeds if already installed)
297        if self.config.panic_handler.enable_structured_logging {
298            let _ = crate::panic_handler::install_panic_handler_with_config(
299                self.config.panic_handler.clone(),
300            );
301        }
302
303        Ok(())
304    }
305
306    /// Check if performance features are enabled
307    #[cfg(feature = "performance-optimized")]
308    pub fn is_performance_enabled(&self) -> bool {
309        self.config.performance.enable_string_interning
310            || self.config.performance.enable_buffer_pooling
311            || self.config.performance.enable_fast_paths
312    }
313
314    #[cfg(not(feature = "performance-optimized"))]
315    pub fn is_performance_enabled(&self) -> bool {
316        false
317    }
318
319    /// Check if correlation features are enabled
320    #[cfg(feature = "correlation-enhanced")]
321    pub fn is_correlation_enabled(&self) -> bool {
322        self.config.correlation.enable_baggage || self.config.correlation.enable_scoped_context
323    }
324
325    #[cfg(not(feature = "correlation-enhanced"))]
326    pub fn is_correlation_enabled(&self) -> bool {
327        false
328    }
329
330    /// Check if convenience features are enabled
331    #[cfg(feature = "convenience")]
332    pub fn is_convenience_enabled(&self) -> bool {
333        self.config.convenience.enable_llm_logging
334            || self.config.convenience.enable_template_logging
335            || self.config.convenience.enable_a2a_logging
336    }
337
338    #[cfg(not(feature = "convenience"))]
339    pub fn is_convenience_enabled(&self) -> bool {
340        false
341    }
342
343    /// Get base observability manager
344    pub fn base(&self) -> &ObservabilityManager {
345        &self.base
346    }
347
348    /// Get enhanced configuration
349    pub fn config(&self) -> &EnhancedObservabilityConfig {
350        &self.config
351    }
352
353    /// Process log entry through all enabled features
354    pub fn process_log_entry(&self, entry: LogEntry) -> Result<LogEntry> {
355        let mut processed_entry = entry;
356
357        // Apply performance optimizations
358        #[cfg(feature = "performance-optimized")]
359        if let Some(ref perf) = self.performance {
360            processed_entry = perf.process_entry(processed_entry)?;
361        }
362
363        // Apply correlation enhancements
364        #[cfg(feature = "correlation-enhanced")]
365        if let Some(ref corr) = self.correlation {
366            processed_entry = corr.process_entry(processed_entry)?;
367        }
368
369        // Apply convenience enhancements
370        #[cfg(feature = "convenience")]
371        if let Some(ref conv) = self.convenience {
372            processed_entry = conv.process_entry(processed_entry)?;
373        }
374
375        Ok(processed_entry)
376    }
377
378    /// Get performance statistics (if enabled)
379    #[cfg(feature = "performance-optimized")]
380    pub fn get_performance_stats(&self) -> Option<crate::performance::PerformanceStats> {
381        self.performance.as_ref().map(|p| p.get_stats())
382    }
383
384    /// Reset performance statistics (if enabled)
385    #[cfg(feature = "performance-optimized")]
386    pub fn reset_performance_stats(&self) -> Result<()> {
387        if let Some(ref perf) = self.performance {
388            perf.reset_stats()?;
389        }
390        Ok(())
391    }
392
393    /// Get panic statistics if panic handler is enabled
394    pub fn get_panic_stats(&self) -> Result<crate::panic_handler::PanicStats> {
395        crate::panic_handler::get_panic_stats()
396    }
397
398    /// Reset panic statistics if panic handler is enabled
399    pub fn reset_panic_stats(&self) -> Result<()> {
400        crate::panic_handler::reset_panic_stats()
401    }
402
403    /// Get manager capabilities
404    pub fn capabilities(&self) -> Vec<&'static str> {
405        let mut caps = vec!["enhanced_logging"];
406
407        if self.is_performance_enabled() {
408            caps.push("performance_optimization");
409        }
410        if self.is_correlation_enabled() {
411            caps.push("correlation_enhancement");
412        }
413        if self.is_convenience_enabled() {
414            caps.push("convenience_apis");
415        }
416        if self.config.panic_handler.enable_structured_logging {
417            caps.push("panic_handling");
418        }
419
420        caps
421    }
422}
423
424/// Create performance extension from configuration
425pub fn create_performance_extension(
426    config: EnhancedObservabilityConfig,
427) -> Result<PerformanceExtension> {
428    PerformanceExtension::new(config)
429}
430
431/// Create performance extension from configuration file
432pub fn create_performance_extension_from_config(config_path: &str) -> Result<PerformanceExtension> {
433    let config_str = std::fs::read_to_string(config_path).map_err(|e| {
434        StructuredLoggingError::enhanced_config(format!("Failed to read config file: {}", e))
435    })?;
436    let config = EnhancedObservabilityConfig::from_json(&config_str)?;
437    PerformanceExtension::new(config)
438}
439
440#[cfg(test)]
441mod tests {
442    use super::*;
443
444    #[test]
445    fn test_enhanced_config_default() {
446        let config = EnhancedObservabilityConfig::default();
447
448        // Verify base config exists
449        assert_eq!(config.base.level, "info");
450        assert_eq!(config.base.format, "compact");
451        assert!(config.base.structured);
452    }
453
454    #[test]
455    fn test_enhanced_config_with_base() {
456        let base = ObservabilityConfig {
457            level: "debug".to_string(),
458            format: "json".to_string(),
459            structured: true,
460            context_enrichment: true,
461            default_context: std::collections::HashMap::new(),
462        };
463
464        let config = EnhancedObservabilityConfig::with_base(base);
465        assert_eq!(config.base.level, "debug");
466        assert_eq!(config.base.format, "json");
467    }
468
469    #[cfg(feature = "performance-optimized")]
470    #[test]
471    fn test_performance_config_default() {
472        let config = PerformanceConfig::default();
473        assert!(config.enable_string_interning);
474        assert!(config.enable_buffer_pooling);
475        assert!(config.enable_fast_paths);
476    }
477
478    #[test]
479    fn test_performance_extension_creation() {
480        let config = EnhancedObservabilityConfig::default();
481        let result = PerformanceExtension::new(config);
482        assert!(result.is_ok());
483    }
484
485    #[test]
486    fn test_config_serialization() {
487        let config = EnhancedObservabilityConfig::default();
488        let json = config.to_json().unwrap();
489        let restored = EnhancedObservabilityConfig::from_json(&json).unwrap();
490
491        assert_eq!(config.base.level, restored.base.level);
492        assert_eq!(config.base.format, restored.base.format);
493    }
494}