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
use std::io::Write;
use std::sync::{Arc, Mutex};
use serde_json::{Map, Value};
pub trait EventSink: Send + Sync {
fn write_line(&self, line: &str);
}
pub struct StdoutSink;
impl EventSink for StdoutSink {
fn write_line(&self, line: &str) {
let mut out = std::io::stdout().lock();
let _ = writeln!(out, "{line}");
let _ = out.flush();
}
}
#[derive(Default)]
pub struct CaptureSink {
lines: Mutex<Vec<String>>,
}
impl CaptureSink {
pub fn lines(&self) -> Vec<String> {
self.lines.lock().expect("capture sink poisoned").clone()
}
}
impl EventSink for CaptureSink {
fn write_line(&self, line: &str) {
self.lines
.lock()
.expect("capture sink poisoned")
.push(line.to_owned());
}
}
#[derive(Clone)]
pub struct Output {
sink: Arc<dyn EventSink>,
}
impl Output {
pub fn new(sink: Arc<dyn EventSink>) -> Self {
Self { sink }
}
pub fn stdout() -> Self {
Self::new(Arc::new(StdoutSink))
}
pub fn emit(&self, event: &str, fields: Value) {
let mut map = Map::new();
map.insert("event".into(), Value::String(event.into()));
if let Value::Object(fields) = fields {
for (key, value) in fields {
if key == "event" {
continue;
}
map.insert(key, value);
}
}
self.sink.write_line(&Value::Object(map).to_string());
}
pub fn emit_value(&self, value: Value) {
self.sink.write_line(&value.to_string());
}
}