Skip to main content

standard_logging_demo/
standard_logging_demo.rs

1//! Demonstration of Standard Rust Logging Integration
2//!
3//! This example shows how the observability extension enables agents to use
4//! standard Rust logging macros (log::info!, log::debug!, etc.) with
5//! structured output and context enrichment.
6
7use log::{debug, error, info, warn};
8use observability_core::{LogLevel, ObservabilityConfig, ObservabilityManager};
9use serde_json::json;
10
11#[cfg(feature = "structured-logging")]
12fn main() -> Result<(), Box<dyn std::error::Error>> {
13    println!("šŸš€ Standard Rust Logging Integration Demo");
14    println!("==========================================\n");
15
16    // 1. Create observability configuration
17    let config = ObservabilityConfig {
18        level: "debug".to_string(),
19        format: "compact".to_string(),
20        structured: true,
21        context_enrichment: true,
22        default_context: [
23            ("agent_id".to_string(), json!("demo-agent")),
24            ("version".to_string(), json!("0.1.0")),
25        ]
26        .into_iter()
27        .collect(),
28    };
29
30    println!("šŸ“‹ Configuration:");
31    println!("   Level: {}", config.level);
32    println!("   Format: {}", config.format);
33    println!("   Structured: {}", config.structured);
34    println!("   Context Enrichment: {}\n", config.context_enrichment);
35
36    // 2. Create and initialize the observability manager
37    let mut manager = ObservabilityManager::new(config)?;
38    manager.initialize()?;
39
40    println!("āœ… Observability manager initialized");
41    println!("āœ… Standard Rust logging is now hooked into structured logging\n");
42
43    // 3. Demonstrate standard logging macros
44    println!("šŸŽÆ Testing standard Rust logging macros:\n");
45
46    // Standard log macros - these now go through our structured logging system!
47    info!("Agent startup completed successfully");
48    debug!("Loading configuration from file: config.json");
49    warn!("High memory usage detected: 85% of available memory");
50    error!("Failed to connect to external service: timeout after 30s");
51
52    println!("\nšŸ” The log entries above were processed through:");
53    println!("   āœ“ Timestamp processor (added current timestamp)");
54    println!("   āœ“ Context enricher (added agent_id, version)");
55    println!("   āœ“ Structured fields processor (formatted as JSON)");
56    println!("   āœ“ WASM stdout adapter (output to console)\n");
57
58    // 4. Demonstrate different log levels
59    println!("šŸ“Š Testing different log levels:");
60
61    if log::log_enabled!(log::Level::Trace) {
62        log::trace!("This is a trace message - very detailed debugging");
63    } else {
64        println!("   (Trace level disabled - current level is debug)");
65    }
66
67    log::debug!("Debugging information about internal state");
68    log::info!("General information about agent operation");
69    log::warn!("Warning about potential issues");
70    log::error!("Error that occurred during processing");
71
72    println!("\nšŸŽØ Each level is automatically formatted with appropriate styling\n");
73
74    // 5. Demonstrate context enrichment
75    println!("šŸ”— Testing context enrichment:");
76
77    // These would be enriched with the default context fields we configured
78    info!("Processing user request");
79    debug!("Executing business logic");
80
81    println!("   āœ“ Each log entry includes agent_id and version from default context\n");
82
83    // 6. Show capabilities
84    println!("šŸ› ļø  Manager capabilities:");
85    for capability in manager.capabilities() {
86        println!("   āœ“ {}", capability);
87    }
88
89    println!("\nšŸŽÆ Key Benefits:");
90    println!("   • No custom logging methods needed - use familiar log::info! etc.");
91    println!("   • Automatic structured JSON output with context enrichment");
92    println!("   • WASM-compatible with fast startup times");
93    println!("   • Hexagonal architecture allows swapping transports/formatters");
94    println!("   • Processor chain pattern inspired by Python's structlog");
95
96    println!("\n✨ Integration Complete!");
97    println!("   Agents can now use standard Rust logging with zero boilerplate");
98
99    Ok(())
100}
101
102#[cfg(not(feature = "structured-logging"))]
103fn main() {
104    println!("This example requires the 'structured-logging' feature.");
105    println!("Run with: cargo run --example standard_logging_demo --features structured-logging");
106}
107
108// Helper function for testing in different contexts
109#[cfg(feature = "structured-logging")]
110pub fn demonstrate_logging_in_function() -> Result<(), Box<dyn std::error::Error>> {
111    // This shows that logging works from any function after initialization
112    log::info!("Logging from a separate function works perfectly!");
113    log::debug!("Function context is automatically captured");
114    Ok(())
115}
116
117#[cfg(test)]
118mod tests {
119    use super::*;
120
121    #[test]
122    #[cfg(feature = "structured-logging")]
123    fn test_configuration_creation() {
124        let config = ObservabilityConfig::default();
125        assert_eq!(config.level, "info");
126        assert!(config.structured);
127    }
128
129    #[test]
130    #[cfg(feature = "structured-logging")]
131    fn test_manager_creation() {
132        let config = ObservabilityConfig::default();
133        let manager = ObservabilityManager::new(config);
134        assert!(manager.is_ok());
135    }
136
137    #[test]
138    #[cfg(feature = "structured-logging")]
139    fn test_level_checking() {
140        let config = ObservabilityConfig {
141            level: "warn".to_string(),
142            ..Default::default()
143        };
144        let manager = ObservabilityManager::new(config).unwrap();
145
146        // These would require initialization to work properly in practice
147        assert!(manager.is_enabled(LogLevel::Error));
148        assert!(manager.is_enabled(LogLevel::Warn));
149        assert!(!manager.is_enabled(LogLevel::Info)); // Below threshold
150    }
151}