1use crate::error::{Result, StructuredLoggingError};
7use observability_core::{LogEntry, domain::LogProcessor, ports::MetricsPort};
8use serde_json::Value;
9
10#[cfg(test)]
11use observability_core::{domain::create_log_entry, traits::LogLevel};
12
13thread_local! {
15 static LLM_CONTEXT: std::cell::RefCell<Option<LLMContext>> = std::cell::RefCell::new(None);
16 static TEMPLATE_CONTEXT: std::cell::RefCell<Option<TemplateContext>> = std::cell::RefCell::new(None);
17 static A2A_CONTEXT: std::cell::RefCell<Option<A2AContext>> = std::cell::RefCell::new(None);
18 static REQUEST_CONTEXT: std::cell::RefCell<Option<RequestContext>> = std::cell::RefCell::new(None);
19 static METRICS_PORT: std::cell::RefCell<Option<Box<dyn MetricsPort>>> = std::cell::RefCell::new(None);
21}
22
23#[derive(Debug, Clone)]
25pub struct LLMContext {
26 pub model: String,
27 pub component: String,
28 pub operation_start: String, }
30
31#[derive(Debug, Clone)]
33pub struct TemplateContext {
34 pub engine: String,
35 pub template: String,
36 pub component: String,
37 pub operation_start: String,
38}
39
40#[derive(Debug, Clone)]
42pub struct A2AContext {
43 pub message_type: String,
44 pub from_agent: String,
45 pub to_agent: String,
46 pub component: String,
47 pub operation_start: String,
48}
49
50#[derive(Debug, Clone)]
52pub struct RequestContext {
53 pub request_id: String,
54 pub user_id: Option<String>,
55 pub session_id: Option<String>,
56 pub operation_start: String,
57}
58
59#[macro_export]
61macro_rules! llm_context {
62 ($model:expr_2021) => {
63 $crate::convenience::set_llm_context($model, "openai_client_wasm");
64 };
65 ($model:expr_2021, component: $component:expr_2021) => {
66 $crate::convenience::set_llm_context($model, $component);
67 };
68}
69
70#[macro_export]
72macro_rules! template_context {
73 ($engine:expr_2021, $template:expr_2021) => {
74 $crate::convenience::set_template_context($engine, $template, "template_engines");
75 };
76 ($engine:expr_2021, $template:expr_2021, component: $component:expr_2021) => {
77 $crate::convenience::set_template_context($engine, $template, $component);
78 };
79}
80
81#[macro_export]
83macro_rules! a2a_context {
84 ($message_type:expr_2021, from: $from:expr_2021, to: $to:expr_2021) => {
85 $crate::convenience::set_a2a_context($message_type, $from, $to, "a2a_jsonrpc_server");
86 };
87 ($message_type:expr_2021, from: $from:expr_2021, to: $to:expr_2021, component: $component:expr_2021) => {
88 $crate::convenience::set_a2a_context($message_type, $from, $to, $component);
89 };
90}
91
92#[macro_export]
94macro_rules! clear_context {
95 () => {
96 $crate::convenience::clear_all_contexts();
97 };
98}
99
100pub fn set_llm_context(model: &str, component: &str) {
102 let context = LLMContext {
103 model: model.to_string(),
104 component: component.to_string(),
105 operation_start: get_current_timestamp(),
106 };
107 LLM_CONTEXT.with(|ctx| {
108 *ctx.borrow_mut() = Some(context);
109 });
110}
111
112pub fn set_template_context(engine: &str, template: &str, component: &str) {
114 let context = TemplateContext {
115 engine: engine.to_string(),
116 template: template.to_string(),
117 component: component.to_string(),
118 operation_start: get_current_timestamp(),
119 };
120 TEMPLATE_CONTEXT.with(|ctx| {
121 *ctx.borrow_mut() = Some(context);
122 });
123}
124
125pub fn set_a2a_context(message_type: &str, from_agent: &str, to_agent: &str, component: &str) {
127 let context = A2AContext {
128 message_type: message_type.to_string(),
129 from_agent: from_agent.to_string(),
130 to_agent: to_agent.to_string(),
131 component: component.to_string(),
132 operation_start: get_current_timestamp(),
133 };
134 A2A_CONTEXT.with(|ctx| {
135 *ctx.borrow_mut() = Some(context);
136 });
137}
138
139pub fn set_request_context(request_id: &str, user_id: Option<&str>, session_id: Option<&str>) {
141 let context = RequestContext {
142 request_id: request_id.to_string(),
143 user_id: user_id.map(|s| s.to_string()),
144 session_id: session_id.map(|s| s.to_string()),
145 operation_start: get_current_timestamp(),
146 };
147 REQUEST_CONTEXT.with(|ctx| {
148 *ctx.borrow_mut() = Some(context);
149 });
150}
151
152pub fn clear_llm_context() {
154 LLM_CONTEXT.with(|ctx| *ctx.borrow_mut() = None);
155}
156
157pub fn clear_template_context() {
159 TEMPLATE_CONTEXT.with(|ctx| *ctx.borrow_mut() = None);
160}
161
162pub fn clear_a2a_context() {
164 A2A_CONTEXT.with(|ctx| *ctx.borrow_mut() = None);
165}
166
167pub fn clear_request_context() {
169 REQUEST_CONTEXT.with(|ctx| *ctx.borrow_mut() = None);
170}
171
172pub fn clear_all_contexts() {
174 clear_llm_context();
175 clear_template_context();
176 clear_a2a_context();
177 clear_request_context();
178}
179
180fn get_current_timestamp() -> String {
182 chrono::Utc::now().to_rfc3339()
184}
185
186#[derive(Debug)]
188pub struct DomainContextProcessor;
189
190impl DomainContextProcessor {
191 pub fn new() -> Self {
192 Self
193 }
194
195 fn enhance_llm_entry(&self, mut entry: LogEntry) -> Result<LogEntry> {
197 LLM_CONTEXT.with(|ctx| {
198 if let Some(llm_ctx) = ctx.borrow().as_ref() {
199 if let serde_json::Value::Object(ref mut map) = entry.fields {
201 map.insert(
202 "component".to_string(),
203 Value::String(llm_ctx.component.clone()),
204 );
205 map.insert("model".to_string(), Value::String(llm_ctx.model.clone()));
206 map.insert(
207 "operation".to_string(),
208 Value::String("llm_request".to_string()),
209 );
210
211 if let Some(duration_val) = map.get("duration") {
213 if let Some(duration_ms) = duration_val.as_u64() {
214 map.insert(
215 "duration_ms".to_string(),
216 Value::Number(duration_ms.into()),
217 );
218 }
219 }
220
221 if let Some(tokens_val) = map.get("tokens") {
223 map.insert("tokens".to_string(), tokens_val.clone());
224 }
225
226 if let Some(status_val) = map.get("status") {
228 map.insert("status".to_string(), status_val.clone());
229 }
230 }
231
232 if entry.message == "info" || entry.message.is_empty() {
234 entry.message = "LLM request completed".to_string();
235 }
236 }
237 });
238 Ok(entry)
239 }
240
241 fn enhance_template_entry(&self, mut entry: LogEntry) -> Result<LogEntry> {
243 TEMPLATE_CONTEXT.with(|ctx| {
244 if let Some(template_ctx) = ctx.borrow().as_ref() {
245 if let serde_json::Value::Object(ref mut map) = entry.fields {
247 map.insert(
248 "component".to_string(),
249 Value::String(template_ctx.component.clone()),
250 );
251 map.insert(
252 "engine".to_string(),
253 Value::String(template_ctx.engine.clone()),
254 );
255 map.insert(
256 "template".to_string(),
257 Value::String(template_ctx.template.clone()),
258 );
259 map.insert(
260 "operation".to_string(),
261 Value::String("template_render".to_string()),
262 );
263
264 if let Some(duration_val) = map.get("duration") {
266 if let Some(duration_ms) = duration_val.as_u64() {
267 map.insert(
268 "duration_ms".to_string(),
269 Value::Number(duration_ms.into()),
270 );
271 }
272 }
273
274 if let Some(size_val) = map.get("size") {
275 map.insert("output_size".to_string(), size_val.clone());
276 }
277 }
278
279 if entry.message == "info" || entry.message.is_empty() {
281 entry.message = "Template rendered".to_string();
282 }
283 }
284 });
285 Ok(entry)
286 }
287
288 fn enhance_a2a_entry(&self, mut entry: LogEntry) -> Result<LogEntry> {
290 A2A_CONTEXT.with(|ctx| {
291 if let Some(a2a_ctx) = ctx.borrow().as_ref() {
292 if let serde_json::Value::Object(ref mut map) = entry.fields {
294 map.insert(
295 "component".to_string(),
296 Value::String(a2a_ctx.component.clone()),
297 );
298 map.insert(
299 "message_type".to_string(),
300 Value::String(a2a_ctx.message_type.clone()),
301 );
302 map.insert(
303 "from_agent".to_string(),
304 Value::String(a2a_ctx.from_agent.clone()),
305 );
306 map.insert(
307 "to_agent".to_string(),
308 Value::String(a2a_ctx.to_agent.clone()),
309 );
310 map.insert(
311 "protocol".to_string(),
312 Value::String("json-rpc-2.0".to_string()),
313 );
314 map.insert(
315 "operation".to_string(),
316 Value::String("a2a_message".to_string()),
317 );
318
319 if let Some(duration_val) = map.get("duration") {
321 if let Some(duration_ms) = duration_val.as_u64() {
322 map.insert(
323 "duration_ms".to_string(),
324 Value::Number(duration_ms.into()),
325 );
326 }
327 }
328 }
329
330 if entry.message == "info" || entry.message.is_empty() {
332 entry.message = "A2A message processed".to_string();
333 }
334 }
335 });
336 Ok(entry)
337 }
338
339 fn auto_detect_and_enhance(&self, mut entry: LogEntry) -> Result<LogEntry> {
341 if let serde_json::Value::Object(ref map) = entry.fields {
342 if map.contains_key("model") || map.contains_key("tokens") {
344 if let serde_json::Value::Object(ref mut fields) = entry.fields {
345 fields.insert(
346 "operation".to_string(),
347 Value::String("llm_request".to_string()),
348 );
349 if entry.message == "info" || entry.message.is_empty() {
350 entry.message = "LLM request completed".to_string();
351 }
352 }
353 }
354 else if map.contains_key("engine") || map.contains_key("template") {
356 if let serde_json::Value::Object(ref mut fields) = entry.fields {
357 fields.insert(
358 "operation".to_string(),
359 Value::String("template_render".to_string()),
360 );
361 if entry.message == "info" || entry.message.is_empty() {
362 entry.message = "Template rendered".to_string();
363 }
364 }
365 }
366 else if map.contains_key("from_agent")
368 || map.contains_key("to_agent")
369 || map.contains_key("message_type")
370 {
371 if let serde_json::Value::Object(ref mut fields) = entry.fields {
372 fields.insert(
373 "operation".to_string(),
374 Value::String("a2a_message".to_string()),
375 );
376 fields.insert(
377 "protocol".to_string(),
378 Value::String("json-rpc-2.0".to_string()),
379 );
380 if entry.message == "info" || entry.message.is_empty() {
381 entry.message = "A2A message processed".to_string();
382 }
383 }
384 }
385 }
386 Ok(entry)
387 }
388}
389
390impl Default for DomainContextProcessor {
391 fn default() -> Self {
392 Self::new()
393 }
394}
395
396impl LogProcessor for DomainContextProcessor {
397 fn process(&self, entry: LogEntry) -> observability_core::ObservabilityResult<LogEntry> {
398 let mut enhanced_entry = entry;
399
400 enhanced_entry = self
402 .enhance_llm_entry(enhanced_entry)
403 .map_err(|e| observability_core::ObservabilityError::logging(e.to_string()))?;
404
405 enhanced_entry = self
406 .enhance_template_entry(enhanced_entry)
407 .map_err(|e| observability_core::ObservabilityError::logging(e.to_string()))?;
408
409 enhanced_entry = self
410 .enhance_a2a_entry(enhanced_entry)
411 .map_err(|e| observability_core::ObservabilityError::logging(e.to_string()))?;
412
413 enhanced_entry = self
415 .auto_detect_and_enhance(enhanced_entry)
416 .map_err(|e| observability_core::ObservabilityError::logging(e.to_string()))?;
417
418 Ok(enhanced_entry)
419 }
420
421 fn name(&self) -> &'static str {
422 "domain_context"
423 }
424}
425
426pub struct ConvenienceManager {
428 processor: DomainContextProcessor,
429}
430
431impl ConvenienceManager {
432 pub fn new() -> Result<Self> {
434 Ok(Self {
435 processor: DomainContextProcessor::new(),
436 })
437 }
438
439 pub fn process_entry(&self, entry: LogEntry) -> Result<LogEntry> {
441 self.processor
442 .process(entry)
443 .map_err(StructuredLoggingError::from)
444 }
445
446 pub fn get_processor(&self) -> &DomainContextProcessor {
448 &self.processor
449 }
450}
451
452pub fn set_metrics_port(port: Box<dyn MetricsPort>) {
454 METRICS_PORT.with(|p| {
455 *p.borrow_mut() = Some(port);
456 });
457}
458
459pub fn clear_metrics_port() {
461 METRICS_PORT.with(|p| {
462 *p.borrow_mut() = None;
463 });
464}
465
466pub fn emit_llm_request_duration(model: &str, duration_ms: u64) -> Result<()> {
468 METRICS_PORT.with(|port| {
469 match *port.borrow() {
470 Some(ref metrics_port) => {
471 let metric_name = "llm_request_duration_ms";
472 let _ = metrics_port
473 .emit_histogram_simple(metric_name, duration_ms as f64)
474 .map_err(|e| println!("[METRICS_ERROR] Failed to emit {}: {}", metric_name, e));
475 }
476 _ => {
477 LLM_CONTEXT.with(|ctx| match *ctx.borrow() {
479 Some(ref context) => {
480 println!(
481 "[METRIC] llm_request_duration_ms {} model={} component={}",
482 duration_ms, model, context.component
483 );
484 }
485 _ => {
486 println!(
487 "[METRIC] llm_request_duration_ms {} model={}",
488 duration_ms, model
489 );
490 }
491 });
492 }
493 }
494 });
495 Ok(())
496}
497
498pub fn emit_llm_tokens_used(model: &str, tokens: u32) -> Result<()> {
500 METRICS_PORT.with(|port| {
501 match *port.borrow() {
502 Some(ref metrics_port) => {
503 let metric_name = "llm_tokens_used";
504 let _ = metrics_port
505 .emit_counter_simple(metric_name, tokens as f64)
506 .map_err(|e| println!("[METRICS_ERROR] Failed to emit {}: {}", metric_name, e));
507 }
508 _ => {
509 LLM_CONTEXT.with(|ctx| match *ctx.borrow() {
511 Some(ref context) => {
512 println!(
513 "[METRIC] llm_tokens_used {} model={} component={}",
514 tokens, model, context.component
515 );
516 }
517 _ => {
518 println!("[METRIC] llm_tokens_used {} model={}", tokens, model);
519 }
520 });
521 }
522 }
523 });
524 Ok(())
525}
526
527pub fn emit_a2a_message_latency(latency_ms: u64) -> Result<()> {
529 METRICS_PORT.with(|port| {
530 match *port.borrow() {
531 Some(ref metrics_port) => {
532 let metric_name = "a2a_message_latency_ms";
533 let _ = metrics_port
534 .emit_histogram_simple(metric_name, latency_ms as f64)
535 .map_err(|e| println!("[METRICS_ERROR] Failed to emit {}: {}", metric_name, e));
536 }
537 _ => {
538 A2A_CONTEXT.with(|ctx| match *ctx.borrow() {
540 Some(ref context) => {
541 println!(
542 "[METRIC] a2a_message_latency_ms {} from={} to={} type={}",
543 latency_ms, context.from_agent, context.to_agent, context.message_type
544 );
545 }
546 _ => {
547 println!("[METRIC] a2a_message_latency_ms {}", latency_ms);
548 }
549 });
550 }
551 }
552 });
553 Ok(())
554}
555
556pub fn emit_template_render_duration(template: &str, duration_ms: u64) -> Result<()> {
558 METRICS_PORT.with(|port| {
559 match *port.borrow() { Some(ref metrics_port) => {
560 let metric_name = "template_render_duration_ms";
561 let _ = metrics_port.emit_histogram_simple(metric_name, duration_ms as f64)
562 .map_err(|e| println!("[METRICS_ERROR] Failed to emit {}: {}", metric_name, e));
563 } _ => {
564 TEMPLATE_CONTEXT.with(|ctx| {
566 match *ctx.borrow() { Some(ref context) => {
567 println!("[METRIC] template_render_duration_ms {} engine={} template={} component={}",
568 duration_ms, context.engine, template, context.component);
569 } _ => {
570 println!("[METRIC] template_render_duration_ms {} template={}", duration_ms, template);
571 }}
572 });
573 }}
574 });
575 Ok(())
576}
577
578pub fn emit_request_duration(duration_ms: u64) -> Result<()> {
580 METRICS_PORT.with(|port| {
581 match *port.borrow() {
582 Some(ref metrics_port) => {
583 let metric_name = "request_duration_ms";
584 let _ = metrics_port
585 .emit_histogram_simple(metric_name, duration_ms as f64)
586 .map_err(|e| println!("[METRICS_ERROR] Failed to emit {}: {}", metric_name, e));
587 }
588 _ => {
589 REQUEST_CONTEXT.with(|ctx| match *ctx.borrow() {
591 Some(ref context) => {
592 let mut metric = format!(
593 "[METRIC] request_duration_ms {} request_id={}",
594 duration_ms, context.request_id
595 );
596 if let Some(ref user_id) = context.user_id {
597 metric.push_str(&format!(" user_id={}", user_id));
598 }
599 if let Some(ref session_id) = context.session_id {
600 metric.push_str(&format!(" session_id={}", session_id));
601 }
602 println!("{}", metric);
603 }
604 _ => {
605 println!("[METRIC] request_duration_ms {}", duration_ms);
606 }
607 });
608 }
609 }
610 });
611 Ok(())
612}
613
614pub fn emit_counter(name: &str, value: f64) -> Result<()> {
616 METRICS_PORT.with(|port| {
617 match *port.borrow() {
618 Some(ref metrics_port) => {
619 let _ = metrics_port.emit_counter_simple(name, value).map_err(|e| {
620 println!("[METRICS_ERROR] Failed to emit counter {}: {}", name, e)
621 });
622 }
623 _ => {
624 let mut labels = Vec::new();
626
627 LLM_CONTEXT.with(|ctx| {
629 if let Some(ref context) = *ctx.borrow() {
630 labels.push(format!("llm_component={}", context.component));
631 }
632 });
633
634 A2A_CONTEXT.with(|ctx| {
635 if let Some(ref context) = *ctx.borrow() {
636 labels.push(format!("from_agent={}", context.from_agent));
637 labels.push(format!("to_agent={}", context.to_agent));
638 labels.push(format!("message_type={}", context.message_type));
639 }
640 });
641
642 TEMPLATE_CONTEXT.with(|ctx| {
643 if let Some(ref context) = *ctx.borrow() {
644 labels.push(format!("template_engine={}", context.engine));
645 }
646 });
647
648 REQUEST_CONTEXT.with(|ctx| {
649 if let Some(ref context) = *ctx.borrow() {
650 labels.push(format!("request_id={}", context.request_id));
651 if let Some(ref user_id) = context.user_id {
652 labels.push(format!("user_id={}", user_id));
653 }
654 }
655 });
656
657 let labels_str = if labels.is_empty() {
658 String::new()
659 } else {
660 format!(" {}", labels.join(" "))
661 };
662
663 println!("[METRIC] {} counter {}{}", name, value, labels_str);
664 }
665 }
666 });
667 Ok(())
668}
669
670pub fn emit_histogram(name: &str, value: f64) -> Result<()> {
672 METRICS_PORT.with(|port| {
673 match *port.borrow() {
674 Some(ref metrics_port) => {
675 let _ = metrics_port
676 .emit_histogram_simple(name, value)
677 .map_err(|e| {
678 println!("[METRICS_ERROR] Failed to emit histogram {}: {}", name, e)
679 });
680 }
681 _ => {
682 let mut labels = Vec::new();
684
685 LLM_CONTEXT.with(|ctx| {
687 if let Some(ref context) = *ctx.borrow() {
688 labels.push(format!("llm_component={}", context.component));
689 }
690 });
691
692 A2A_CONTEXT.with(|ctx| {
693 if let Some(ref context) = *ctx.borrow() {
694 labels.push(format!("from_agent={}", context.from_agent));
695 labels.push(format!("to_agent={}", context.to_agent));
696 }
697 });
698
699 let labels_str = if labels.is_empty() {
700 String::new()
701 } else {
702 format!(" {}", labels.join(" "))
703 };
704
705 println!("[METRIC] {} histogram {}{}", name, value, labels_str);
706 }
707 }
708 });
709 Ok(())
710}
711
712pub fn log_llm_request(
714 model: &str,
715 duration: web_time::Duration,
716 tokens: u32,
717 status: &str,
718) -> Result<LogEntry> {
719 use observability_core::domain::create_log_entry;
720 use observability_core::traits::LogLevel;
721
722 let entry = create_log_entry(
723 LogLevel::Info,
724 &format!(
725 "LLM request completed: {} tokens in {}ms",
726 tokens,
727 duration.as_millis()
728 ),
729 serde_json::json!({
730 "model": model,
731 "duration_ms": duration.as_millis(),
732 "tokens": tokens,
733 "status": status,
734 "operation": "llm_request",
735 "component": "openai_client_wasm"
736 }),
737 );
738
739 Ok(entry)
740}
741
742pub fn log_template_render(
744 engine: &str,
745 template: &str,
746 duration: web_time::Duration,
747 size: usize,
748 status: &str,
749) -> Result<LogEntry> {
750 use observability_core::domain::create_log_entry;
751 use observability_core::traits::LogLevel;
752
753 let entry = create_log_entry(
754 LogLevel::Info,
755 &format!(
756 "Template rendered: {} using {} in {}ms",
757 template,
758 engine,
759 duration.as_millis()
760 ),
761 serde_json::json!({
762 "engine": engine,
763 "template": template,
764 "duration_ms": duration.as_millis(),
765 "output_size": size,
766 "status": status,
767 "operation": "template_render",
768 "component": "template_engines"
769 }),
770 );
771
772 Ok(entry)
773}
774
775pub fn log_a2a_message(
777 message_type: &str,
778 from_agent: &str,
779 to_agent: &str,
780 duration: Option<web_time::Duration>,
781 status: &str,
782) -> Result<LogEntry> {
783 use observability_core::domain::create_log_entry;
784 use observability_core::traits::LogLevel;
785
786 let mut fields = serde_json::json!({
787 "message_type": message_type,
788 "from_agent": from_agent,
789 "to_agent": to_agent,
790 "status": status,
791 "operation": "a2a_message",
792 "protocol": "json-rpc-2.0",
793 "component": "a2a_jsonrpc_server"
794 });
795
796 if let Some(dur) = duration {
797 fields["duration_ms"] = serde_json::json!(dur.as_millis());
798 }
799
800 let message = if let Some(dur) = duration {
801 format!(
802 "A2A message processed: {} from {} to {} in {}ms",
803 message_type,
804 from_agent,
805 to_agent,
806 dur.as_millis()
807 )
808 } else {
809 format!(
810 "A2A message processed: {} from {} to {}",
811 message_type, from_agent, to_agent
812 )
813 };
814
815 let entry = create_log_entry(LogLevel::Info, &message, fields);
816
817 Ok(entry)
818}
819
820#[macro_export]
822macro_rules! llm_log {
823 ($model:expr_2021, $duration:expr_2021, $tokens:expr_2021, $status:expr_2021) => {
824 $crate::convenience::log_llm_request($model, $duration, $tokens, $status)
825 };
826}
827
828#[macro_export]
829macro_rules! template_log {
830 ($engine:expr_2021, $template:expr_2021, $duration:expr_2021, $size:expr_2021, $status:expr_2021) => {
831 $crate::convenience::log_template_render($engine, $template, $duration, $size, $status)
832 };
833}
834
835#[macro_export]
836macro_rules! a2a_log {
837 ($message_type:expr_2021, $from:expr_2021, $to:expr_2021, $status:expr_2021) => {
838 $crate::convenience::log_a2a_message($message_type, $from, $to, None, $status)
839 };
840}
841
842#[cfg(test)]
843mod tests {
844 use super::*;
845
846 #[test]
847 fn test_llm_context_enhancement() {
848 let processor = DomainContextProcessor::new();
849
850 set_llm_context("gpt-4", "openai_client");
852
853 let entry = create_log_entry(
855 LogLevel::Info,
856 "Request completed",
857 serde_json::json!({
858 "duration": 250,
859 "tokens": 1500,
860 "status": "success"
861 }),
862 );
863
864 let enhanced = processor.process(entry).unwrap();
865
866 if let serde_json::Value::Object(ref map) = enhanced.fields {
868 assert_eq!(
869 map.get("model").unwrap(),
870 &Value::String("gpt-4".to_string())
871 );
872 assert_eq!(
873 map.get("component").unwrap(),
874 &Value::String("openai_client".to_string())
875 );
876 assert_eq!(
877 map.get("operation").unwrap(),
878 &Value::String("llm_request".to_string())
879 );
880 }
881
882 clear_all_contexts();
883 }
884
885 #[test]
886 fn test_template_context_enhancement() {
887 let processor = DomainContextProcessor::new();
888
889 set_template_context("Sailfish", "agent_card.stpl", "template_engine");
891
892 let entry = create_log_entry(
893 LogLevel::Debug,
894 "Render completed",
895 serde_json::json!({
896 "duration": 50,
897 "size": 2048
898 }),
899 );
900
901 let enhanced = processor.process(entry).unwrap();
902
903 if let serde_json::Value::Object(ref map) = enhanced.fields {
904 assert_eq!(
905 map.get("engine").unwrap(),
906 &Value::String("Sailfish".to_string())
907 );
908 assert_eq!(
909 map.get("template").unwrap(),
910 &Value::String("agent_card.stpl".to_string())
911 );
912 assert_eq!(
913 map.get("operation").unwrap(),
914 &Value::String("template_render".to_string())
915 );
916 }
917
918 clear_all_contexts();
919 }
920
921 #[test]
922 fn test_auto_detection() {
923 let processor = DomainContextProcessor::new();
924
925 let entry = create_log_entry(
927 LogLevel::Info,
928 "info",
929 serde_json::json!({
930 "model": "gpt-4",
931 "tokens": 1000
932 }),
933 );
934
935 let enhanced = processor.process(entry).unwrap();
936
937 if let serde_json::Value::Object(ref map) = enhanced.fields {
938 assert_eq!(
939 map.get("operation").unwrap(),
940 &Value::String("llm_request".to_string())
941 );
942 }
943 assert_eq!(enhanced.message, "LLM request completed");
944 }
945}