micromegas_tracing/
test_utils.rs1use crate::dispatch::flush_log_buffer;
4use crate::dispatch::{force_uninit, init_event_dispatch, shutdown_dispatch};
5use crate::event::in_memory_sink::InMemorySink;
6use crate::logs::LogMsgQueueAny;
7use micromegas_transit::HeterogeneousQueue;
8use std::collections::HashMap;
9use std::sync::Arc;
10
11pub struct InMemoryTracingGuard {
20 pub sink: Arc<InMemorySink>,
21}
22
23impl Default for InMemoryTracingGuard {
24 fn default() -> Self {
25 Self::new()
26 }
27}
28
29impl InMemoryTracingGuard {
30 pub fn new() -> Self {
31 let sink = Arc::new(InMemorySink::new());
32 init_event_dispatch(1024, 1024, 1024, sink.clone(), HashMap::new(), true) .expect("Failed to initialize event dispatch");
34 Self { sink }
35 }
36}
37
38impl Drop for InMemoryTracingGuard {
39 fn drop(&mut self) {
40 shutdown_dispatch();
41 unsafe { force_uninit() };
42 }
43}
44
45pub fn init_in_memory_tracing() -> InMemoryTracingGuard {
67 InMemoryTracingGuard::new()
68}
69
70pub struct CapturedLog {
72 pub msg: String,
73 pub properties: Vec<(String, String)>,
75}
76
77impl CapturedLog {
78 pub fn property(&self, name: &str) -> Option<&str> {
80 self.properties
81 .iter()
82 .find(|(k, _)| k == name)
83 .map(|(_, v)| v.as_str())
84 }
85}
86
87pub fn collect_logs(sink: &InMemorySink) -> Vec<CapturedLog> {
90 flush_log_buffer();
91 let state = sink.state.lock().expect("sink lock");
92 let mut out = vec![];
93 for block in &state.log_blocks {
94 for event in block.events.iter() {
95 let (msg, set_id) = match event {
96 LogMsgQueueAny::LogStaticStrEvent(e) => (e.desc.fmt_str.to_owned(), None),
97 LogMsgQueueAny::LogStringEvent(e) => (e.msg.0.clone(), None),
98 LogMsgQueueAny::TaggedLogStaticStrEvent(e) => {
99 (e.desc.fmt_str.to_owned(), Some(e.properties))
100 }
101 LogMsgQueueAny::TaggedLogString(e) => (e.msg.0.clone(), Some(e.properties)),
102 _ => continue,
103 };
104 let properties = set_id
105 .map(|id| {
106 block
107 .dyn_deps
108 .set_properties(id)
109 .into_iter()
110 .map(|(k, v)| (k.to_owned(), v.to_owned()))
111 .collect()
112 })
113 .unwrap_or_default();
114 out.push(CapturedLog { msg, properties });
115 }
116 }
117 out
118}