use core::fmt;
use std::error::Error;
use tracing::field::{Field, Visit};
use super::FATAL;
const MESSAGE_FIELD: &str = "message";
const ERROR_FIELD: &str = "error";
const STACK_FIELD: &str = "exception_stack";
#[derive(Debug, Clone, PartialEq)]
pub(crate) enum PropValue {
Text(String),
Integer(i128),
Float(f64),
Flag(bool),
}
#[derive(Debug, Clone)]
pub(crate) struct ExceptionData {
pub(crate) kind: String,
pub(crate) message: String,
pub(crate) stack: Option<String>,
pub(crate) causes: Option<String>,
}
#[derive(Default)]
pub(crate) struct EventData {
pub(crate) message: String,
pub(crate) exception: Option<ExceptionData>,
pub(crate) fatal: bool,
pub(crate) properties: Vec<(String, PropValue)>,
}
impl EventData {
pub(crate) fn collect(event: &tracing::Event<'_>) -> Self {
let mut collector = Collector::default();
event.record(&mut collector);
collector.finish()
}
}
#[derive(Default)]
struct Collector {
data: EventData,
stack: Option<String>,
}
impl Collector {
fn text_error(&mut self, text: String) {
if self.data.exception.is_none() {
self.data.exception = Some(ExceptionData {
kind: "Error".to_owned(),
message: text,
stack: None,
causes: None,
});
}
}
fn object_error(&mut self, value: &(dyn Error + 'static)) {
if self.data.exception.is_some() {
return;
}
let debug = format!("{value:?}");
self.data.exception = Some(ExceptionData {
kind: short_type(&debug).to_owned(),
message: value.to_string(),
stack: None,
causes: causes(value),
});
}
fn finish(mut self) -> EventData {
if let Some(stack) = self.stack
&& let Some(exception) = self.data.exception.as_mut()
{
exception.stack = Some(stack);
}
self.data
}
}
impl Visit for Collector {
fn record_str(&mut self, field: &Field, value: &str) {
match field.name() {
MESSAGE_FIELD => self.data.message = value.to_owned(),
ERROR_FIELD => self.text_error(value.to_owned()),
STACK_FIELD => self.stack = Some(value.to_owned()),
FATAL => {}
name => self
.data
.properties
.push((name.to_owned(), PropValue::Text(value.to_owned()))),
}
}
fn record_error(&mut self, field: &Field, value: &(dyn Error + 'static)) {
if field.name() == ERROR_FIELD {
self.object_error(value);
} else {
self.data
.properties
.push((field.name().to_owned(), PropValue::Text(value.to_string())));
}
}
fn record_debug(&mut self, field: &Field, value: &dyn fmt::Debug) {
let text = format!("{value:?}");
match field.name() {
MESSAGE_FIELD => self.data.message = text,
ERROR_FIELD => self.text_error(text),
STACK_FIELD => self.stack = Some(text),
FATAL => {}
name => self
.data
.properties
.push((name.to_owned(), PropValue::Text(text))),
}
}
fn record_bool(&mut self, field: &Field, value: bool) {
if field.name() == FATAL {
self.data.fatal = value;
} else {
self.data
.properties
.push((field.name().to_owned(), PropValue::Flag(value)));
}
}
fn record_i64(&mut self, field: &Field, value: i64) {
self.integer(field, i128::from(value));
}
fn record_u64(&mut self, field: &Field, value: u64) {
self.integer(field, i128::from(value));
}
fn record_i128(&mut self, field: &Field, value: i128) {
self.integer(field, value);
}
fn record_u128(&mut self, field: &Field, value: u128) {
match i128::try_from(value) {
Ok(number) => self.integer(field, number),
Err(_) => self
.data
.properties
.push((field.name().to_owned(), PropValue::Text(value.to_string()))),
}
}
fn record_f64(&mut self, field: &Field, value: f64) {
self.data
.properties
.push((field.name().to_owned(), PropValue::Float(value)));
}
}
impl Collector {
fn integer(&mut self, field: &Field, value: i128) {
self.data
.properties
.push((field.name().to_owned(), PropValue::Integer(value)));
}
}
pub(crate) fn short_type(debug: &str) -> &str {
let end = debug.find(['(', '{', ':']).unwrap_or(debug.len());
debug[..end].trim_end()
}
fn causes(value: &(dyn Error + 'static)) -> Option<String> {
let mut lines = Vec::new();
let mut current = value.source();
while let Some(error) = current {
let debug = format!("{error:?}");
lines.push(format!("{}: {}", short_type(&debug), error));
current = error.source();
}
if lines.is_empty() {
None
} else {
Some(lines.join("\n"))
}
}
pub(crate) fn capture_text(exception: &ExceptionData) -> String {
let mut text = format!("{}: {}", exception.kind, exception.message);
if let Some(stack) = &exception.stack {
for line in stack.split('\n') {
text.push_str("\n ");
text.push_str(line);
}
}
if let Some(causes) = &exception.causes {
for line in causes.split('\n') {
text.push_str("\n Caused by: ");
text.push_str(line);
}
}
text
}