Skip to main content

utopia_span/exporter/
stdout.rs

1//! Spans as JSON lines.
2
3use std::io::Write;
4
5use php_std::json::{self, Flags};
6use php_std::{Array, ArrayKey, Value as Php};
7
8use super::{Exporter, Sampler, Streams, kept};
9use crate::Span;
10
11/// Writes each span as one line of JSON (NDJSON): `level` and `action`
12/// first, then every attribute, then the error (`error.type`,
13/// `error.message`, `error.code`, `error.file`, `error.line`, `error.trace`
14/// with at most `max_trace_frames` frames, `error.trace_truncated`). Spans
15/// with an error go to standard error, the others to standard output.
16///
17/// Invalid UTF-8 is replaced with U+FFFD and a value that cannot be encoded
18/// becomes `null`, so one bad attribute cannot drop the whole record; when
19/// the record still cannot be encoded, a line naming the failure (`level`,
20/// `action`, `error.type`, `export.error`) is written instead.
21///
22/// PHP: `Utopia\Span\Exporter\Stdout`.
23///
24/// ```
25/// use std::io::Write;
26/// use std::sync::{Arc, Mutex};
27/// use utopia_span::{Exporter, Span, Stdout};
28///
29/// #[derive(Clone, Default)]
30/// struct Buffer(Arc<Mutex<Vec<u8>>>);
31/// impl Write for Buffer {
32///     fn write(&mut self, b: &[u8]) -> std::io::Result<usize> { self.0.lock().unwrap().write(b) }
33///     fn flush(&mut self) -> std::io::Result<()> { Ok(()) }
34/// }
35///
36/// let out = Buffer::default();
37/// let exporter = Stdout::new().writers(Box::new(out.clone()), Box::new(std::io::sink()));
38/// let span = Span::new("job");
39/// span.set("span.trace_id", "t").set("span.id", "s").set("span.started_at", 1.5).set("level", "info");
40/// exporter.export(&span);
41///
42/// let line = String::from_utf8(out.0.lock().unwrap().clone()).unwrap();
43/// assert_eq!(line, "{\"level\":\"info\",\"action\":\"job\",\"span.trace_id\":\"t\",\"span.id\":\"s\",\"span.started_at\":1.5}\n");
44/// ```
45///
46/// ```php
47/// use Utopia\Span\Exporter\Stdout;
48/// use Utopia\Span\Span;
49///
50/// $span = new Span('job');
51/// $span->set('span.trace_id', 't')->set('span.id', 's')->set('span.started_at', 1.5)->set('level', 'info');
52/// (new Stdout())->export($span);
53/// // {"level":"info","action":"job","span.trace_id":"t","span.id":"s","span.started_at":1.5}
54/// ```
55pub struct Stdout {
56    sampler: Sampler,
57    max_trace_frames: usize,
58    streams: Streams,
59}
60
61impl Default for Stdout {
62    fn default() -> Self {
63        Self::new()
64    }
65}
66
67impl std::fmt::Debug for Stdout {
68    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
69        f.debug_struct("Stdout").field("max_trace_frames", &self.max_trace_frames).finish()
70    }
71}
72
73impl Stdout {
74    /// An exporter of every span, with at most 3 stack frames per error,
75    /// writing to the process's standard output and error.
76    ///
77    /// PHP: `new Stdout()`.
78    pub fn new() -> Self {
79        Self { sampler: Box::new(|_| true), max_trace_frames: 3, streams: Streams::standard() }
80    }
81
82    /// Exports only the spans `sampler` accepts.
83    ///
84    /// PHP: the `$sampler` argument.
85    pub fn sampler(mut self, sampler: impl Fn(&Span) -> bool + Send + Sync + 'static) -> Self {
86        self.sampler = Box::new(sampler);
87        self
88    }
89
90    /// Prints at most `frames` stack frames of an error.
91    ///
92    /// PHP: the `$maxTraceFrames` argument.
93    pub fn max_trace_frames(mut self, frames: usize) -> Self {
94        self.max_trace_frames = frames;
95        self
96    }
97
98    /// Writes spans to `out`, and spans with an error to `err`.
99    ///
100    /// PHP: the `$stdout` and `$stderr` arguments.
101    pub fn writers(mut self, out: Box<dyn Write + Send>, err: Box<dyn Write + Send>) -> Self {
102        self.streams = Streams::new(out, err);
103        self
104    }
105
106    /// The line this exporter writes for `span` (without its newline), or
107    /// `None` when neither it nor the fallback line can be encoded.
108    pub fn line(&self, span: &Span) -> Option<String> {
109        let mut attributes = Array::<php_std::Never>::default();
110        span.with_attributes(|attrs| {
111            for (key, value) in attrs {
112                attributes.set(ArrayKey::from(&**key), value.to_php());
113            }
114        });
115        let mut data = Array::default();
116        let level = ArrayKey::from("level");
117        if let Some(level_value) = attributes.remove(&level) {
118            data.set(level, level_value);
119        }
120        data.set(ArrayKey::from("action"), Php::from(span.action()));
121        for (key, value) in attributes {
122            if !data.contains_key(&key) {
123                data.set(key, value);
124            }
125        }
126        if let Some(error) = span.error() {
127            let set = |data: &mut Array, key: &str, value: Php| {
128                data.set(ArrayKey::from(key), value);
129            };
130            set(&mut data, "error.type", Php::from(error.class()));
131            set(&mut data, "error.message", Php::Str(error.message_bytes().into()));
132            set(&mut data, "error.code", Php::Int(error.code_value()));
133            set(&mut data, "error.file", Php::from(error.file()));
134            set(&mut data, "error.line", Php::Int(i64::from(error.line())));
135            let frames = error.frames();
136            let trace: Array = frames[..kept(frames.len(), self.max_trace_frames)]
137                .iter()
138                .map(|frame| {
139                    let mut f = Array::default();
140                    f.set(ArrayKey::from("file"), frame.file.as_deref().map_or(Php::Null, Php::from));
141                    f.set(ArrayKey::from("line"), frame.line.map_or(Php::Null, |l| Php::Int(i64::from(l))));
142                    f.set(ArrayKey::from("function"), Php::from(frame.function.as_str()));
143                    Php::Array(f)
144                })
145                .collect();
146            set(&mut data, "error.trace", Php::Array(trace));
147            if frames.len() > self.max_trace_frames {
148                set(&mut data, "error.trace_truncated", Php::Int((frames.len() - self.max_trace_frames) as i64));
149            }
150        }
151        // Substitute invalid UTF-8 and keep partial output so one bad
152        // attribute cannot drop the whole record.
153        let flags = Flags::UNESCAPED_SLASHES | Flags::INVALID_UTF8_SUBSTITUTE | Flags::PARTIAL_OUTPUT_ON_ERROR;
154        let error = match json::encode(&Php::Array(data.clone()), flags, json::DEFAULT_DEPTH) {
155            Ok(line) => return Some(line),
156            Err(json::Error::Partial { json, .. }) => return Some(json),
157            Err(e) => e,
158        };
159        let mut fallback = Array::default();
160        let field = |key: &str| data.get(&ArrayKey::from(key)).cloned().unwrap_or(Php::Null);
161        fallback.set(ArrayKey::from("level"), field("level"));
162        fallback.set(ArrayKey::from("action"), Php::from(span.action()));
163        fallback.set(ArrayKey::from("error.type"), field("error.type"));
164        fallback.set(
165            ArrayKey::from("export.error"),
166            Php::from(format!("Span could not be encoded as JSON: {}", error.message()).as_str()),
167        );
168        match json::encode(&Php::Array(fallback), flags, json::DEFAULT_DEPTH) {
169            Ok(line) | Err(json::Error::Partial { json: line, .. }) => Some(line),
170            Err(_) => None,
171        }
172    }
173}
174
175impl Exporter for Stdout {
176    fn sample(&self, span: &Span) -> bool {
177        (self.sampler)(span)
178    }
179
180    fn export(&self, span: &Span) {
181        let Some(mut line) = self.line(span) else {
182            return;
183        };
184        line.push('\n');
185        self.streams.write(span.error().is_some(), line.as_bytes());
186    }
187}