use std::io::Write;
use php_std::json::{self, Flags};
use php_std::{Array, ArrayKey, Value as Php};
use super::{Exporter, Sampler, Streams, kept};
use crate::Span;
pub struct Stdout {
sampler: Sampler,
max_trace_frames: usize,
streams: Streams,
}
impl Default for Stdout {
fn default() -> Self {
Self::new()
}
}
impl std::fmt::Debug for Stdout {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Stdout").field("max_trace_frames", &self.max_trace_frames).finish()
}
}
impl Stdout {
pub fn new() -> Self {
Self { sampler: Box::new(|_| true), max_trace_frames: 3, streams: Streams::standard() }
}
pub fn sampler(mut self, sampler: impl Fn(&Span) -> bool + Send + Sync + 'static) -> Self {
self.sampler = Box::new(sampler);
self
}
pub fn max_trace_frames(mut self, frames: usize) -> Self {
self.max_trace_frames = frames;
self
}
pub fn writers(mut self, out: Box<dyn Write + Send>, err: Box<dyn Write + Send>) -> Self {
self.streams = Streams::new(out, err);
self
}
pub fn line(&self, span: &Span) -> Option<String> {
let mut attributes = Array::<php_std::Never>::default();
span.with_attributes(|attrs| {
for (key, value) in attrs {
attributes.set(ArrayKey::from(&**key), value.to_php());
}
});
let mut data = Array::default();
let level = ArrayKey::from("level");
if let Some(level_value) = attributes.remove(&level) {
data.set(level, level_value);
}
data.set(ArrayKey::from("action"), Php::from(span.action()));
for (key, value) in attributes {
if !data.contains_key(&key) {
data.set(key, value);
}
}
if let Some(error) = span.error() {
let set = |data: &mut Array, key: &str, value: Php| {
data.set(ArrayKey::from(key), value);
};
set(&mut data, "error.type", Php::from(error.class()));
set(&mut data, "error.message", Php::Str(error.message_bytes().into()));
set(&mut data, "error.code", Php::Int(error.code_value()));
set(&mut data, "error.file", Php::from(error.file()));
set(&mut data, "error.line", Php::Int(i64::from(error.line())));
let frames = error.frames();
let trace: Array = frames[..kept(frames.len(), self.max_trace_frames)]
.iter()
.map(|frame| {
let mut f = Array::default();
f.set(ArrayKey::from("file"), frame.file.as_deref().map_or(Php::Null, Php::from));
f.set(ArrayKey::from("line"), frame.line.map_or(Php::Null, |l| Php::Int(i64::from(l))));
f.set(ArrayKey::from("function"), Php::from(frame.function.as_str()));
Php::Array(f)
})
.collect();
set(&mut data, "error.trace", Php::Array(trace));
if frames.len() > self.max_trace_frames {
set(&mut data, "error.trace_truncated", Php::Int((frames.len() - self.max_trace_frames) as i64));
}
}
let flags = Flags::UNESCAPED_SLASHES | Flags::INVALID_UTF8_SUBSTITUTE | Flags::PARTIAL_OUTPUT_ON_ERROR;
let error = match json::encode(&Php::Array(data.clone()), flags, json::DEFAULT_DEPTH) {
Ok(line) => return Some(line),
Err(json::Error::Partial { json, .. }) => return Some(json),
Err(e) => e,
};
let mut fallback = Array::default();
let field = |key: &str| data.get(&ArrayKey::from(key)).cloned().unwrap_or(Php::Null);
fallback.set(ArrayKey::from("level"), field("level"));
fallback.set(ArrayKey::from("action"), Php::from(span.action()));
fallback.set(ArrayKey::from("error.type"), field("error.type"));
fallback.set(
ArrayKey::from("export.error"),
Php::from(format!("Span could not be encoded as JSON: {}", error.message()).as_str()),
);
match json::encode(&Php::Array(fallback), flags, json::DEFAULT_DEPTH) {
Ok(line) | Err(json::Error::Partial { json: line, .. }) => Some(line),
Err(_) => None,
}
}
}
impl Exporter for Stdout {
fn sample(&self, span: &Span) -> bool {
(self.sampler)(span)
}
fn export(&self, span: &Span) {
let Some(mut line) = self.line(span) else {
return;
};
line.push('\n');
self.streams.write(span.error().is_some(), line.as_bytes());
}
}