utopia_span/exporter/
stdout.rs1use 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
11pub 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 pub fn new() -> Self {
79 Self { sampler: Box::new(|_| true), max_trace_frames: 3, streams: Streams::standard() }
80 }
81
82 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 pub fn max_trace_frames(mut self, frames: usize) -> Self {
94 self.max_trace_frames = frames;
95 self
96 }
97
98 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 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 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}