pf_structured_logging 0.1.0

Enhanced structured logging with performance optimizations and convenience APIs for SpinKube agents
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
//! Context-aware processors for domain-specific logging operations
//!
//! These processors automatically detect and enhance standard log::info!, log::debug! calls
//! based on context and structured fields, maintaining standard Rust logging interface.

use crate::error::{Result, StructuredLoggingError};
use observability_core::{LogEntry, domain::LogProcessor, ports::MetricsPort};
use serde_json::Value;

#[cfg(test)]
use observability_core::{domain::create_log_entry, traits::LogLevel};

// Thread-local context for domain operations
thread_local! {
    static LLM_CONTEXT: std::cell::RefCell<Option<LLMContext>> = std::cell::RefCell::new(None);
    static TEMPLATE_CONTEXT: std::cell::RefCell<Option<TemplateContext>> = std::cell::RefCell::new(None);
    static A2A_CONTEXT: std::cell::RefCell<Option<A2AContext>> = std::cell::RefCell::new(None);
    static REQUEST_CONTEXT: std::cell::RefCell<Option<RequestContext>> = std::cell::RefCell::new(None);
    /// Thread-local storage for the active MetricsPort implementation
    static METRICS_PORT: std::cell::RefCell<Option<Box<dyn MetricsPort>>> = std::cell::RefCell::new(None);
}

/// Context for LLM operations
#[derive(Debug, Clone)]
pub struct LLMContext {
    pub model: String,
    pub component: String,
    pub operation_start: String, // timestamp string for WASM compatibility
}

/// Context for template operations  
#[derive(Debug, Clone)]
pub struct TemplateContext {
    pub engine: String,
    pub template: String,
    pub component: String,
    pub operation_start: String,
}

/// Context for A2A operations
#[derive(Debug, Clone)]
pub struct A2AContext {
    pub message_type: String,
    pub from_agent: String,
    pub to_agent: String,
    pub component: String,
    pub operation_start: String,
}

/// Context for request operations
#[derive(Debug, Clone)]
pub struct RequestContext {
    pub request_id: String,
    pub user_id: Option<String>,
    pub session_id: Option<String>,
    pub operation_start: String,
}

/// Set LLM context for subsequent standard log calls
#[macro_export]
macro_rules! llm_context {
    ($model:expr_2021) => {
        $crate::convenience::set_llm_context($model, "openai_client_wasm");
    };
    ($model:expr_2021, component: $component:expr_2021) => {
        $crate::convenience::set_llm_context($model, $component);
    };
}

/// Set template context for subsequent standard log calls
#[macro_export]
macro_rules! template_context {
    ($engine:expr_2021, $template:expr_2021) => {
        $crate::convenience::set_template_context($engine, $template, "template_engines");
    };
    ($engine:expr_2021, $template:expr_2021, component: $component:expr_2021) => {
        $crate::convenience::set_template_context($engine, $template, $component);
    };
}

/// Set A2A context for subsequent standard log calls
#[macro_export]
macro_rules! a2a_context {
    ($message_type:expr_2021, from: $from:expr_2021, to: $to:expr_2021) => {
        $crate::convenience::set_a2a_context($message_type, $from, $to, "a2a_jsonrpc_server");
    };
    ($message_type:expr_2021, from: $from:expr_2021, to: $to:expr_2021, component: $component:expr_2021) => {
        $crate::convenience::set_a2a_context($message_type, $from, $to, $component);
    };
}

/// Clear all domain contexts
#[macro_export]
macro_rules! clear_context {
    () => {
        $crate::convenience::clear_all_contexts();
    };
}

/// Set LLM context
pub fn set_llm_context(model: &str, component: &str) {
    let context = LLMContext {
        model: model.to_string(),
        component: component.to_string(),
        operation_start: get_current_timestamp(),
    };
    LLM_CONTEXT.with(|ctx| {
        *ctx.borrow_mut() = Some(context);
    });
}

/// Set template context
pub fn set_template_context(engine: &str, template: &str, component: &str) {
    let context = TemplateContext {
        engine: engine.to_string(),
        template: template.to_string(),
        component: component.to_string(),
        operation_start: get_current_timestamp(),
    };
    TEMPLATE_CONTEXT.with(|ctx| {
        *ctx.borrow_mut() = Some(context);
    });
}

/// Set A2A context
pub fn set_a2a_context(message_type: &str, from_agent: &str, to_agent: &str, component: &str) {
    let context = A2AContext {
        message_type: message_type.to_string(),
        from_agent: from_agent.to_string(),
        to_agent: to_agent.to_string(),
        component: component.to_string(),
        operation_start: get_current_timestamp(),
    };
    A2A_CONTEXT.with(|ctx| {
        *ctx.borrow_mut() = Some(context);
    });
}

/// Set request context
pub fn set_request_context(request_id: &str, user_id: Option<&str>, session_id: Option<&str>) {
    let context = RequestContext {
        request_id: request_id.to_string(),
        user_id: user_id.map(|s| s.to_string()),
        session_id: session_id.map(|s| s.to_string()),
        operation_start: get_current_timestamp(),
    };
    REQUEST_CONTEXT.with(|ctx| {
        *ctx.borrow_mut() = Some(context);
    });
}

/// Clear LLM context only
pub fn clear_llm_context() {
    LLM_CONTEXT.with(|ctx| *ctx.borrow_mut() = None);
}

/// Clear template context only
pub fn clear_template_context() {
    TEMPLATE_CONTEXT.with(|ctx| *ctx.borrow_mut() = None);
}

/// Clear A2A context only
pub fn clear_a2a_context() {
    A2A_CONTEXT.with(|ctx| *ctx.borrow_mut() = None);
}

/// Clear request context only
pub fn clear_request_context() {
    REQUEST_CONTEXT.with(|ctx| *ctx.borrow_mut() = None);
}

/// Clear all contexts
pub fn clear_all_contexts() {
    clear_llm_context();
    clear_template_context();
    clear_a2a_context();
    clear_request_context();
}

/// Get current timestamp as string (WASM compatible)
fn get_current_timestamp() -> String {
    // Use chrono consistently throughout the workspace for timestamps
    chrono::Utc::now().to_rfc3339()
}

/// Processor that automatically enhances standard log calls with domain-specific structure
#[derive(Debug)]
pub struct DomainContextProcessor;

impl DomainContextProcessor {
    pub fn new() -> Self {
        Self
    }

    /// Detect if this is an LLM operation and enhance accordingly
    fn enhance_llm_entry(&self, mut entry: LogEntry) -> Result<LogEntry> {
        LLM_CONTEXT.with(|ctx| {
            if let Some(llm_ctx) = ctx.borrow().as_ref() {
                // Add LLM-specific fields
                if let serde_json::Value::Object(ref mut map) = entry.fields {
                    map.insert(
                        "component".to_string(),
                        Value::String(llm_ctx.component.clone()),
                    );
                    map.insert("model".to_string(), Value::String(llm_ctx.model.clone()));
                    map.insert(
                        "operation".to_string(),
                        Value::String("llm_request".to_string()),
                    );

                    // Extract duration, tokens, status from existing fields if present
                    if let Some(duration_val) = map.get("duration") {
                        if let Some(duration_ms) = duration_val.as_u64() {
                            map.insert(
                                "duration_ms".to_string(),
                                Value::Number(duration_ms.into()),
                            );
                        }
                    }

                    // Auto-detect tokens from fields
                    if let Some(tokens_val) = map.get("tokens") {
                        map.insert("tokens".to_string(), tokens_val.clone());
                    }

                    // Auto-detect status from fields
                    if let Some(status_val) = map.get("status") {
                        map.insert("status".to_string(), status_val.clone());
                    }
                }

                // Enhance message if it's generic
                if entry.message == "info" || entry.message.is_empty() {
                    entry.message = "LLM request completed".to_string();
                }
            }
        });
        Ok(entry)
    }

    /// Detect if this is a template operation and enhance accordingly
    fn enhance_template_entry(&self, mut entry: LogEntry) -> Result<LogEntry> {
        TEMPLATE_CONTEXT.with(|ctx| {
            if let Some(template_ctx) = ctx.borrow().as_ref() {
                // Add template-specific fields
                if let serde_json::Value::Object(ref mut map) = entry.fields {
                    map.insert(
                        "component".to_string(),
                        Value::String(template_ctx.component.clone()),
                    );
                    map.insert(
                        "engine".to_string(),
                        Value::String(template_ctx.engine.clone()),
                    );
                    map.insert(
                        "template".to_string(),
                        Value::String(template_ctx.template.clone()),
                    );
                    map.insert(
                        "operation".to_string(),
                        Value::String("template_render".to_string()),
                    );

                    // Extract duration, size from existing fields if present
                    if let Some(duration_val) = map.get("duration") {
                        if let Some(duration_ms) = duration_val.as_u64() {
                            map.insert(
                                "duration_ms".to_string(),
                                Value::Number(duration_ms.into()),
                            );
                        }
                    }

                    if let Some(size_val) = map.get("size") {
                        map.insert("output_size".to_string(), size_val.clone());
                    }
                }

                // Enhance message if it's generic
                if entry.message == "info" || entry.message.is_empty() {
                    entry.message = "Template rendered".to_string();
                }
            }
        });
        Ok(entry)
    }

    /// Detect if this is an A2A operation and enhance accordingly
    fn enhance_a2a_entry(&self, mut entry: LogEntry) -> Result<LogEntry> {
        A2A_CONTEXT.with(|ctx| {
            if let Some(a2a_ctx) = ctx.borrow().as_ref() {
                // Add A2A-specific fields
                if let serde_json::Value::Object(ref mut map) = entry.fields {
                    map.insert(
                        "component".to_string(),
                        Value::String(a2a_ctx.component.clone()),
                    );
                    map.insert(
                        "message_type".to_string(),
                        Value::String(a2a_ctx.message_type.clone()),
                    );
                    map.insert(
                        "from_agent".to_string(),
                        Value::String(a2a_ctx.from_agent.clone()),
                    );
                    map.insert(
                        "to_agent".to_string(),
                        Value::String(a2a_ctx.to_agent.clone()),
                    );
                    map.insert(
                        "protocol".to_string(),
                        Value::String("json-rpc-2.0".to_string()),
                    );
                    map.insert(
                        "operation".to_string(),
                        Value::String("a2a_message".to_string()),
                    );

                    // Extract duration from existing fields if present
                    if let Some(duration_val) = map.get("duration") {
                        if let Some(duration_ms) = duration_val.as_u64() {
                            map.insert(
                                "duration_ms".to_string(),
                                Value::Number(duration_ms.into()),
                            );
                        }
                    }
                }

                // Enhance message if it's generic
                if entry.message == "info" || entry.message.is_empty() {
                    entry.message = "A2A message processed".to_string();
                }
            }
        });
        Ok(entry)
    }

    /// Auto-detect domain from structured fields (fallback when no context set)
    fn auto_detect_and_enhance(&self, mut entry: LogEntry) -> Result<LogEntry> {
        if let serde_json::Value::Object(ref map) = entry.fields {
            // Detect LLM operation from fields
            if map.contains_key("model") || map.contains_key("tokens") {
                if let serde_json::Value::Object(ref mut fields) = entry.fields {
                    fields.insert(
                        "operation".to_string(),
                        Value::String("llm_request".to_string()),
                    );
                    if entry.message == "info" || entry.message.is_empty() {
                        entry.message = "LLM request completed".to_string();
                    }
                }
            }
            // Detect template operation from fields
            else if map.contains_key("engine") || map.contains_key("template") {
                if let serde_json::Value::Object(ref mut fields) = entry.fields {
                    fields.insert(
                        "operation".to_string(),
                        Value::String("template_render".to_string()),
                    );
                    if entry.message == "info" || entry.message.is_empty() {
                        entry.message = "Template rendered".to_string();
                    }
                }
            }
            // Detect A2A operation from fields
            else if map.contains_key("from_agent")
                || map.contains_key("to_agent")
                || map.contains_key("message_type")
            {
                if let serde_json::Value::Object(ref mut fields) = entry.fields {
                    fields.insert(
                        "operation".to_string(),
                        Value::String("a2a_message".to_string()),
                    );
                    fields.insert(
                        "protocol".to_string(),
                        Value::String("json-rpc-2.0".to_string()),
                    );
                    if entry.message == "info" || entry.message.is_empty() {
                        entry.message = "A2A message processed".to_string();
                    }
                }
            }
        }
        Ok(entry)
    }
}

impl Default for DomainContextProcessor {
    fn default() -> Self {
        Self::new()
    }
}

impl LogProcessor for DomainContextProcessor {
    fn process(&self, entry: LogEntry) -> observability_core::ObservabilityResult<LogEntry> {
        let mut enhanced_entry = entry;

        // Try context-based enhancement first
        enhanced_entry = self
            .enhance_llm_entry(enhanced_entry)
            .map_err(|e| observability_core::ObservabilityError::logging(e.to_string()))?;

        enhanced_entry = self
            .enhance_template_entry(enhanced_entry)
            .map_err(|e| observability_core::ObservabilityError::logging(e.to_string()))?;

        enhanced_entry = self
            .enhance_a2a_entry(enhanced_entry)
            .map_err(|e| observability_core::ObservabilityError::logging(e.to_string()))?;

        // Auto-detect from fields as fallback
        enhanced_entry = self
            .auto_detect_and_enhance(enhanced_entry)
            .map_err(|e| observability_core::ObservabilityError::logging(e.to_string()))?;

        Ok(enhanced_entry)
    }

    fn name(&self) -> &'static str {
        "domain_context"
    }
}

/// Convenience manager that integrates domain-aware processing into the processor chain
pub struct ConvenienceManager {
    processor: DomainContextProcessor,
}

impl ConvenienceManager {
    /// Create new convenience manager
    pub fn new() -> Result<Self> {
        Ok(Self {
            processor: DomainContextProcessor::new(),
        })
    }

    /// Process log entry through domain-aware enhancement
    pub fn process_entry(&self, entry: LogEntry) -> Result<LogEntry> {
        self.processor
            .process(entry)
            .map_err(StructuredLoggingError::from)
    }

    /// Get the domain context processor for integration with processor chain
    pub fn get_processor(&self) -> &DomainContextProcessor {
        &self.processor
    }
}

/// Set the active MetricsPort implementation
pub fn set_metrics_port(port: Box<dyn MetricsPort>) {
    METRICS_PORT.with(|p| {
        *p.borrow_mut() = Some(port);
    });
}

/// Clear the active MetricsPort implementation
pub fn clear_metrics_port() {
    METRICS_PORT.with(|p| {
        *p.borrow_mut() = None;
    });
}

/// Emit an LLM request duration metric with context
pub fn emit_llm_request_duration(model: &str, duration_ms: u64) -> Result<()> {
    METRICS_PORT.with(|port| {
        match *port.borrow() {
            Some(ref metrics_port) => {
                let metric_name = "llm_request_duration_ms";
                let _ = metrics_port
                    .emit_histogram_simple(metric_name, duration_ms as f64)
                    .map_err(|e| println!("[METRICS_ERROR] Failed to emit {}: {}", metric_name, e));
            }
            _ => {
                // Fallback to stdout if no MetricsPort is available
                LLM_CONTEXT.with(|ctx| match *ctx.borrow() {
                    Some(ref context) => {
                        println!(
                            "[METRIC] llm_request_duration_ms {} model={} component={}",
                            duration_ms, model, context.component
                        );
                    }
                    _ => {
                        println!(
                            "[METRIC] llm_request_duration_ms {} model={}",
                            duration_ms, model
                        );
                    }
                });
            }
        }
    });
    Ok(())
}

/// Emit an LLM token usage metric with context
pub fn emit_llm_tokens_used(model: &str, tokens: u32) -> Result<()> {
    METRICS_PORT.with(|port| {
        match *port.borrow() {
            Some(ref metrics_port) => {
                let metric_name = "llm_tokens_used";
                let _ = metrics_port
                    .emit_counter_simple(metric_name, tokens as f64)
                    .map_err(|e| println!("[METRICS_ERROR] Failed to emit {}: {}", metric_name, e));
            }
            _ => {
                // Fallback to stdout if no MetricsPort is available
                LLM_CONTEXT.with(|ctx| match *ctx.borrow() {
                    Some(ref context) => {
                        println!(
                            "[METRIC] llm_tokens_used {} model={} component={}",
                            tokens, model, context.component
                        );
                    }
                    _ => {
                        println!("[METRIC] llm_tokens_used {} model={}", tokens, model);
                    }
                });
            }
        }
    });
    Ok(())
}

/// Emit an A2A message latency metric with context
pub fn emit_a2a_message_latency(latency_ms: u64) -> Result<()> {
    METRICS_PORT.with(|port| {
        match *port.borrow() {
            Some(ref metrics_port) => {
                let metric_name = "a2a_message_latency_ms";
                let _ = metrics_port
                    .emit_histogram_simple(metric_name, latency_ms as f64)
                    .map_err(|e| println!("[METRICS_ERROR] Failed to emit {}: {}", metric_name, e));
            }
            _ => {
                // Fallback to stdout if no MetricsPort is available
                A2A_CONTEXT.with(|ctx| match *ctx.borrow() {
                    Some(ref context) => {
                        println!(
                            "[METRIC] a2a_message_latency_ms {} from={} to={} type={}",
                            latency_ms, context.from_agent, context.to_agent, context.message_type
                        );
                    }
                    _ => {
                        println!("[METRIC] a2a_message_latency_ms {}", latency_ms);
                    }
                });
            }
        }
    });
    Ok(())
}

/// Emit a template render duration metric with context  
pub fn emit_template_render_duration(template: &str, duration_ms: u64) -> Result<()> {
    METRICS_PORT.with(|port| {
        match *port.borrow() { Some(ref metrics_port) => {
            let metric_name = "template_render_duration_ms";
            let _ = metrics_port.emit_histogram_simple(metric_name, duration_ms as f64)
                .map_err(|e| println!("[METRICS_ERROR] Failed to emit {}: {}", metric_name, e));
        } _ => {
            // Fallback to stdout if no MetricsPort is available
            TEMPLATE_CONTEXT.with(|ctx| {
                match *ctx.borrow() { Some(ref context) => {
                    println!("[METRIC] template_render_duration_ms {} engine={} template={} component={}", 
                             duration_ms, context.engine, template, context.component);
                } _ => {
                    println!("[METRIC] template_render_duration_ms {} template={}", duration_ms, template);
                }}
            });
        }}
    });
    Ok(())
}

/// Emit request processing duration metric with context
pub fn emit_request_duration(duration_ms: u64) -> Result<()> {
    METRICS_PORT.with(|port| {
        match *port.borrow() {
            Some(ref metrics_port) => {
                let metric_name = "request_duration_ms";
                let _ = metrics_port
                    .emit_histogram_simple(metric_name, duration_ms as f64)
                    .map_err(|e| println!("[METRICS_ERROR] Failed to emit {}: {}", metric_name, e));
            }
            _ => {
                // Fallback to stdout if no MetricsPort is available
                REQUEST_CONTEXT.with(|ctx| match *ctx.borrow() {
                    Some(ref context) => {
                        let mut metric = format!(
                            "[METRIC] request_duration_ms {} request_id={}",
                            duration_ms, context.request_id
                        );
                        if let Some(ref user_id) = context.user_id {
                            metric.push_str(&format!(" user_id={}", user_id));
                        }
                        if let Some(ref session_id) = context.session_id {
                            metric.push_str(&format!(" session_id={}", session_id));
                        }
                        println!("{}", metric);
                    }
                    _ => {
                        println!("[METRIC] request_duration_ms {}", duration_ms);
                    }
                });
            }
        }
    });
    Ok(())
}

/// Generic counter metric with automatic context detection
pub fn emit_counter(name: &str, value: f64) -> Result<()> {
    METRICS_PORT.with(|port| {
        match *port.borrow() {
            Some(ref metrics_port) => {
                let _ = metrics_port.emit_counter_simple(name, value).map_err(|e| {
                    println!("[METRICS_ERROR] Failed to emit counter {}: {}", name, e)
                });
            }
            _ => {
                // Fallback to stdout with context detection
                let mut labels = Vec::new();

                // Auto-detect active contexts and add as labels
                LLM_CONTEXT.with(|ctx| {
                    if let Some(ref context) = *ctx.borrow() {
                        labels.push(format!("llm_component={}", context.component));
                    }
                });

                A2A_CONTEXT.with(|ctx| {
                    if let Some(ref context) = *ctx.borrow() {
                        labels.push(format!("from_agent={}", context.from_agent));
                        labels.push(format!("to_agent={}", context.to_agent));
                        labels.push(format!("message_type={}", context.message_type));
                    }
                });

                TEMPLATE_CONTEXT.with(|ctx| {
                    if let Some(ref context) = *ctx.borrow() {
                        labels.push(format!("template_engine={}", context.engine));
                    }
                });

                REQUEST_CONTEXT.with(|ctx| {
                    if let Some(ref context) = *ctx.borrow() {
                        labels.push(format!("request_id={}", context.request_id));
                        if let Some(ref user_id) = context.user_id {
                            labels.push(format!("user_id={}", user_id));
                        }
                    }
                });

                let labels_str = if labels.is_empty() {
                    String::new()
                } else {
                    format!(" {}", labels.join(" "))
                };

                println!("[METRIC] {} counter {}{}", name, value, labels_str);
            }
        }
    });
    Ok(())
}

/// Generic histogram metric with automatic context detection
pub fn emit_histogram(name: &str, value: f64) -> Result<()> {
    METRICS_PORT.with(|port| {
        match *port.borrow() {
            Some(ref metrics_port) => {
                let _ = metrics_port
                    .emit_histogram_simple(name, value)
                    .map_err(|e| {
                        println!("[METRICS_ERROR] Failed to emit histogram {}: {}", name, e)
                    });
            }
            _ => {
                // Fallback to stdout with context detection
                let mut labels = Vec::new();

                // Auto-detect active contexts (same logic as emit_counter)
                LLM_CONTEXT.with(|ctx| {
                    if let Some(ref context) = *ctx.borrow() {
                        labels.push(format!("llm_component={}", context.component));
                    }
                });

                A2A_CONTEXT.with(|ctx| {
                    if let Some(ref context) = *ctx.borrow() {
                        labels.push(format!("from_agent={}", context.from_agent));
                        labels.push(format!("to_agent={}", context.to_agent));
                    }
                });

                let labels_str = if labels.is_empty() {
                    String::new()
                } else {
                    format!(" {}", labels.join(" "))
                };

                println!("[METRIC] {} histogram {}{}", name, value, labels_str);
            }
        }
    });
    Ok(())
}

/// Convenience function to log LLM requests with structured format
pub fn log_llm_request(
    model: &str,
    duration: web_time::Duration,
    tokens: u32,
    status: &str,
) -> Result<LogEntry> {
    use observability_core::domain::create_log_entry;
    use observability_core::traits::LogLevel;

    let entry = create_log_entry(
        LogLevel::Info,
        &format!(
            "LLM request completed: {} tokens in {}ms",
            tokens,
            duration.as_millis()
        ),
        serde_json::json!({
            "model": model,
            "duration_ms": duration.as_millis(),
            "tokens": tokens,
            "status": status,
            "operation": "llm_request",
            "component": "openai_client_wasm"
        }),
    );

    Ok(entry)
}

/// Convenience function to log template rendering with structured format
pub fn log_template_render(
    engine: &str,
    template: &str,
    duration: web_time::Duration,
    size: usize,
    status: &str,
) -> Result<LogEntry> {
    use observability_core::domain::create_log_entry;
    use observability_core::traits::LogLevel;

    let entry = create_log_entry(
        LogLevel::Info,
        &format!(
            "Template rendered: {} using {} in {}ms",
            template,
            engine,
            duration.as_millis()
        ),
        serde_json::json!({
            "engine": engine,
            "template": template,
            "duration_ms": duration.as_millis(),
            "output_size": size,
            "status": status,
            "operation": "template_render",
            "component": "template_engines"
        }),
    );

    Ok(entry)
}

/// Convenience function to log A2A messages with structured format
pub fn log_a2a_message(
    message_type: &str,
    from_agent: &str,
    to_agent: &str,
    duration: Option<web_time::Duration>,
    status: &str,
) -> Result<LogEntry> {
    use observability_core::domain::create_log_entry;
    use observability_core::traits::LogLevel;

    let mut fields = serde_json::json!({
        "message_type": message_type,
        "from_agent": from_agent,
        "to_agent": to_agent,
        "status": status,
        "operation": "a2a_message",
        "protocol": "json-rpc-2.0",
        "component": "a2a_jsonrpc_server"
    });

    if let Some(dur) = duration {
        fields["duration_ms"] = serde_json::json!(dur.as_millis());
    }

    let message = if let Some(dur) = duration {
        format!(
            "A2A message processed: {} from {} to {} in {}ms",
            message_type,
            from_agent,
            to_agent,
            dur.as_millis()
        )
    } else {
        format!(
            "A2A message processed: {} from {} to {}",
            message_type, from_agent, to_agent
        )
    };

    let entry = create_log_entry(LogLevel::Info, &message, fields);

    Ok(entry)
}

/// Convenience macros for structured logging
#[macro_export]
macro_rules! llm_log {
    ($model:expr_2021, $duration:expr_2021, $tokens:expr_2021, $status:expr_2021) => {
        $crate::convenience::log_llm_request($model, $duration, $tokens, $status)
    };
}

#[macro_export]
macro_rules! template_log {
    ($engine:expr_2021, $template:expr_2021, $duration:expr_2021, $size:expr_2021, $status:expr_2021) => {
        $crate::convenience::log_template_render($engine, $template, $duration, $size, $status)
    };
}

#[macro_export]
macro_rules! a2a_log {
    ($message_type:expr_2021, $from:expr_2021, $to:expr_2021, $status:expr_2021) => {
        $crate::convenience::log_a2a_message($message_type, $from, $to, None, $status)
    };
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_llm_context_enhancement() {
        let processor = DomainContextProcessor::new();

        // Set LLM context
        set_llm_context("gpt-4", "openai_client");

        // Create a basic log entry
        let entry = create_log_entry(
            LogLevel::Info,
            "Request completed",
            serde_json::json!({
                "duration": 250,
                "tokens": 1500,
                "status": "success"
            }),
        );

        let enhanced = processor.process(entry).unwrap();

        // Check that LLM-specific fields were added
        if let serde_json::Value::Object(ref map) = enhanced.fields {
            assert_eq!(
                map.get("model").unwrap(),
                &Value::String("gpt-4".to_string())
            );
            assert_eq!(
                map.get("component").unwrap(),
                &Value::String("openai_client".to_string())
            );
            assert_eq!(
                map.get("operation").unwrap(),
                &Value::String("llm_request".to_string())
            );
        }

        clear_all_contexts();
    }

    #[test]
    fn test_template_context_enhancement() {
        let processor = DomainContextProcessor::new();

        // Set template context
        set_template_context("Sailfish", "agent_card.stpl", "template_engine");

        let entry = create_log_entry(
            LogLevel::Debug,
            "Render completed",
            serde_json::json!({
                "duration": 50,
                "size": 2048
            }),
        );

        let enhanced = processor.process(entry).unwrap();

        if let serde_json::Value::Object(ref map) = enhanced.fields {
            assert_eq!(
                map.get("engine").unwrap(),
                &Value::String("Sailfish".to_string())
            );
            assert_eq!(
                map.get("template").unwrap(),
                &Value::String("agent_card.stpl".to_string())
            );
            assert_eq!(
                map.get("operation").unwrap(),
                &Value::String("template_render".to_string())
            );
        }

        clear_all_contexts();
    }

    #[test]
    fn test_auto_detection() {
        let processor = DomainContextProcessor::new();

        // Test auto-detection without context
        let entry = create_log_entry(
            LogLevel::Info,
            "info",
            serde_json::json!({
                "model": "gpt-4",
                "tokens": 1000
            }),
        );

        let enhanced = processor.process(entry).unwrap();

        if let serde_json::Value::Object(ref map) = enhanced.fields {
            assert_eq!(
                map.get("operation").unwrap(),
                &Value::String("llm_request".to_string())
            );
        }
        assert_eq!(enhanced.message, "LLM request completed");
    }
}