Skip to main content

ObservabilityManager

Struct ObservabilityManager 

Source
pub struct ObservabilityManager { /* private fields */ }
Expand description

Core observability manager

This provides structured logging integration with standard Rust logging macros (log::info!, log::debug!, etc.) without external extension system dependencies

ImplementationsΒ§

SourceΒ§

impl ObservabilityManager

Source

pub fn new(config: ObservabilityConfig) -> ObservabilityResult<Self>

Create a new observability manager with configuration

Examples found in repository?
examples/standard_logging_demo.rs (line 37)
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}
More examples
Hide additional examples
examples/tracing_and_kv_demo.rs (lines 21-27)
15fn main() -> Result<(), Box<dyn std::error::Error>> {
16    println!("πŸš€ Tracing Integration and Structured Fields Demo");
17    println!("================================================\n");
18
19    // 0) Initialize standard Rust logging (log::*) via the singleton manager.
20    // This keeps the example safe (no stack-pointer logger installation).
21    let mut manager = ObservabilityManager::new(ObservabilityConfig {
22        level: "debug".to_string(),
23        format: "compact".to_string(),
24        structured: true,
25        context_enrichment: true,
26        default_context: Default::default(),
27    })?;
28    manager.initialize()?;
29
30    // 1. Set up tracing integration
31    println!("πŸ”§ Setting up tracing integration...");
32    let tracing_subscriber = TracingIntegrationBuilder::new()
33        .with_processor_chain(observability_core::domain::build_enhanced_processor_chain())
34        .with_transport(Arc::new(WasmStdoutAdapter::with_compact_formatter()))
35        .with_level_filter(observability_core::traits::LogLevel::Debug)
36        .build()?;
37
38    // Set as global tracing subscriber
39    tracing::subscriber::set_global_default(tracing_subscriber)
40        .map_err(|e| format!("Failed to set tracing subscriber: {}", e))?;
41
42    println!("βœ… Tracing integration active\n");
43
44    // 2. Demo tracing events
45    println!("πŸ“Š Testing tracing events:");
46    println!("-------------------------");
47
48    let span = span!(Level::INFO, "demo_operation", operation_id = "op-123");
49    let _enter = span.enter();
50
51    info!(target: "demo", user_id = "user-456", session = "sess-789", "Operation started");
52    debug!(items = 42, size = 1024, "Processing data");
53
54    // Nested span
55    {
56        let nested_span = span!(Level::DEBUG, "data_processing", batch_id = "batch-001");
57        let _nested_enter = nested_span.enter();
58
59        info!(records = 100, duration_ms = 250, "Processing batch");
60        debug!(errors = 0, warnings = 2, "Validation complete");
61    }
62
63    info!(
64        status = "success",
65        total_time_ms = 500,
66        "Operation completed"
67    );
68
69    if false {
70        error!(
71            error_code = 500,
72            details = "Connection timeout",
73            "This would be an error"
74        );
75    }
76
77    println!("βœ… Tracing events logged with structured fields and span context\n");
78
79    // 3. Demo structured fields with standard log macros
80    println!("πŸ“ Testing structured fields with standard log macros:");
81    println!("-----------------------------------------------------");
82
83    // Standard log messages.
84    // (KV-style structured fields are supported by the core pipeline, but we keep this example
85    // syntax conservative to compile across toolchains.)
86    log::info!("User login successful");
87    log::debug!("Database query executed");
88    log::warn!("High memory usage detected");
89
90    println!("βœ… Standard log macros processed through LogKvExtractor\n");
91
92    // 4. Demo mixed usage
93    println!("πŸ”„ Testing mixed tracing and log usage:");
94    println!("---------------------------------------");
95
96    let mixed_span = span!(Level::INFO, "mixed_operation", request_id = "req-999");
97    let _mixed_enter = mixed_span.enter();
98
99    // Tracing event
100    info!(
101        endpoint = "/api/users",
102        method = "GET",
103        "Processing request"
104    );
105
106    // Standard log messages
107    log::info!("Authentication successful");
108
109    // Tracing debug
110    debug!(cache_key = "user:123", hit = true, "Cache lookup");
111
112    // Standard log debug
113    log::debug!("Response prepared");
114
115    info!(
116        status = "success",
117        response_time_ms = 89,
118        "Request completed"
119    );
120
121    println!("βœ… Mixed tracing and log usage working together\n");
122
123    println!("πŸŽ‰ Demo completed successfully!");
124    println!("\nπŸ’‘ Key Features Demonstrated:");
125    println!("   ✨ Tracing events β†’ structured logs with span context");
126    println!("   πŸ”‘ log::info!(\"msg\"; \"key\" => value) β†’ automatic kv extraction");
127    println!("   πŸ”— Unified processing through hexagonal architecture");
128    println!("   πŸ“Š Enhanced processor chain with metadata enrichment");
129    println!("   🎯 Both tracing and log work together seamlessly");
130
131    Ok(())
132}
Source

pub fn initialize(&mut self) -> ObservabilityResult<()>

Initialize global logging (convenience method)

Examples found in repository?
examples/standard_logging_demo.rs (line 38)
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}
More examples
Hide additional examples
examples/tracing_and_kv_demo.rs (line 28)
15fn main() -> Result<(), Box<dyn std::error::Error>> {
16    println!("πŸš€ Tracing Integration and Structured Fields Demo");
17    println!("================================================\n");
18
19    // 0) Initialize standard Rust logging (log::*) via the singleton manager.
20    // This keeps the example safe (no stack-pointer logger installation).
21    let mut manager = ObservabilityManager::new(ObservabilityConfig {
22        level: "debug".to_string(),
23        format: "compact".to_string(),
24        structured: true,
25        context_enrichment: true,
26        default_context: Default::default(),
27    })?;
28    manager.initialize()?;
29
30    // 1. Set up tracing integration
31    println!("πŸ”§ Setting up tracing integration...");
32    let tracing_subscriber = TracingIntegrationBuilder::new()
33        .with_processor_chain(observability_core::domain::build_enhanced_processor_chain())
34        .with_transport(Arc::new(WasmStdoutAdapter::with_compact_formatter()))
35        .with_level_filter(observability_core::traits::LogLevel::Debug)
36        .build()?;
37
38    // Set as global tracing subscriber
39    tracing::subscriber::set_global_default(tracing_subscriber)
40        .map_err(|e| format!("Failed to set tracing subscriber: {}", e))?;
41
42    println!("βœ… Tracing integration active\n");
43
44    // 2. Demo tracing events
45    println!("πŸ“Š Testing tracing events:");
46    println!("-------------------------");
47
48    let span = span!(Level::INFO, "demo_operation", operation_id = "op-123");
49    let _enter = span.enter();
50
51    info!(target: "demo", user_id = "user-456", session = "sess-789", "Operation started");
52    debug!(items = 42, size = 1024, "Processing data");
53
54    // Nested span
55    {
56        let nested_span = span!(Level::DEBUG, "data_processing", batch_id = "batch-001");
57        let _nested_enter = nested_span.enter();
58
59        info!(records = 100, duration_ms = 250, "Processing batch");
60        debug!(errors = 0, warnings = 2, "Validation complete");
61    }
62
63    info!(
64        status = "success",
65        total_time_ms = 500,
66        "Operation completed"
67    );
68
69    if false {
70        error!(
71            error_code = 500,
72            details = "Connection timeout",
73            "This would be an error"
74        );
75    }
76
77    println!("βœ… Tracing events logged with structured fields and span context\n");
78
79    // 3. Demo structured fields with standard log macros
80    println!("πŸ“ Testing structured fields with standard log macros:");
81    println!("-----------------------------------------------------");
82
83    // Standard log messages.
84    // (KV-style structured fields are supported by the core pipeline, but we keep this example
85    // syntax conservative to compile across toolchains.)
86    log::info!("User login successful");
87    log::debug!("Database query executed");
88    log::warn!("High memory usage detected");
89
90    println!("βœ… Standard log macros processed through LogKvExtractor\n");
91
92    // 4. Demo mixed usage
93    println!("πŸ”„ Testing mixed tracing and log usage:");
94    println!("---------------------------------------");
95
96    let mixed_span = span!(Level::INFO, "mixed_operation", request_id = "req-999");
97    let _mixed_enter = mixed_span.enter();
98
99    // Tracing event
100    info!(
101        endpoint = "/api/users",
102        method = "GET",
103        "Processing request"
104    );
105
106    // Standard log messages
107    log::info!("Authentication successful");
108
109    // Tracing debug
110    debug!(cache_key = "user:123", hit = true, "Cache lookup");
111
112    // Standard log debug
113    log::debug!("Response prepared");
114
115    info!(
116        status = "success",
117        response_time_ms = 89,
118        "Request completed"
119    );
120
121    println!("βœ… Mixed tracing and log usage working together\n");
122
123    println!("πŸŽ‰ Demo completed successfully!");
124    println!("\nπŸ’‘ Key Features Demonstrated:");
125    println!("   ✨ Tracing events β†’ structured logs with span context");
126    println!("   πŸ”‘ log::info!(\"msg\"; \"key\" => value) β†’ automatic kv extraction");
127    println!("   πŸ”— Unified processing through hexagonal architecture");
128    println!("   πŸ“Š Enhanced processor chain with metadata enrichment");
129    println!("   🎯 Both tracing and log work together seamlessly");
130
131    Ok(())
132}
Source

pub fn config(&self) -> &ObservabilityConfig

Get current configuration

Source

pub fn is_enabled(&self, level: LogLevel) -> bool

Check if logging is enabled for a level

Source

pub fn global_logger() -> Option<Arc<StandardLogAdapter>>

Get the global logger instance (always available with singleton pattern)

Source

pub fn capabilities(&self) -> Vec<String>

Get capabilities as strings

Examples found in repository?
examples/standard_logging_demo.rs (line 85)
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}

Trait ImplementationsΒ§

SourceΒ§

impl Default for ObservabilityManager

SourceΒ§

fn default() -> Self

Returns the β€œdefault value” for a type. Read more

Auto Trait ImplementationsΒ§

Blanket ImplementationsΒ§

SourceΒ§

impl<T> Any for T
where T: 'static + ?Sized,

SourceΒ§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
SourceΒ§

impl<T> Borrow<T> for T
where T: ?Sized,

SourceΒ§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
SourceΒ§

impl<T> BorrowMut<T> for T
where T: ?Sized,

SourceΒ§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
SourceΒ§

impl<T> From<T> for T

SourceΒ§

fn from(t: T) -> T

Returns the argument unchanged.

SourceΒ§

impl<T> Instrument for T

SourceΒ§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
SourceΒ§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
SourceΒ§

impl<T, U> Into<U> for T
where U: From<T>,

SourceΒ§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

SourceΒ§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

SourceΒ§

type Error = Infallible

The type returned in the event of a conversion error.
SourceΒ§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
SourceΒ§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

SourceΒ§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
SourceΒ§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
SourceΒ§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

SourceΒ§

fn vzip(self) -> V

SourceΒ§

impl<T> WithSubscriber for T

SourceΒ§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
SourceΒ§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more