use core::fmt::Write;
use super::event_data::PropValue;
use super::row::Row;
use super::timestamp;
use crate::telemetry::level::Level;
const LEVEL_WIDTH: usize = 5;
const CORRELATION_WIDTH: usize = 6;
pub(crate) fn line(row: &Row, color: bool, out: &mut String) {
timestamp::format_into(out, row.moment);
out.push(' ');
write_level(out, row.level, color);
for _ in level_name(row.level).len()..LEVEL_WIDTH {
out.push(' ');
}
out.push_str(" ");
write_correlation(out, &row.correlation_id);
out.push(' ');
out.push_str(&row.message);
for (key, value) in &row.properties {
out.push(' ');
out.push_str(key);
out.push('=');
text_value(out, value);
}
if let Some(exception) = &row.exception {
let _ = write!(
out,
"\nEXCEPTION OCCURRED: {}: {}",
exception.kind, exception.message
);
if let Some(causes) = &exception.causes {
for cause in causes.split('\n') {
out.push_str("\n Caused by: ");
out.push_str(cause);
}
}
if let Some(stack) = &exception.stack {
for frame in stack.split('\n') {
out.push_str("\n ");
out.push_str(frame);
}
}
}
}
fn write_level(out: &mut String, level: Level, color: bool) {
let name = level_name(level);
if color {
let _ = write!(out, "\u{1b}[{}m{name}\u{1b}[0m", color_code(level));
} else {
out.push_str(name);
}
}
fn level_name(level: Level) -> &'static str {
match level {
Level::Trace => "TRACE",
Level::Debug => "DEBUG",
Level::Info => "INFO",
Level::Warn => "WARN",
Level::Error => "ERROR",
Level::Fatal => "FATAL",
Level::Off => "",
}
}
fn color_code(level: Level) -> &'static str {
match level {
Level::Trace => "90",
Level::Debug => "37",
Level::Info => "32",
Level::Warn => "33",
Level::Error => "31",
Level::Fatal => "41;97",
Level::Off => "0",
}
}
fn write_correlation(out: &mut String, correlation_id: &Option<String>) {
let mut written = 0;
if let Some(id) = correlation_id {
for character in id.chars().take(CORRELATION_WIDTH) {
out.push(character);
written += 1;
}
}
for _ in written..CORRELATION_WIDTH {
out.push(' ');
}
}
fn text_value(out: &mut String, value: &PropValue) {
match value {
PropValue::Text(text) => {
if text.contains(' ') || text.contains('"') || text.contains('=') {
let _ = write!(out, "{text:?}");
} else {
out.push_str(text);
}
}
PropValue::Integer(number) => {
let _ = write!(out, "{number}");
}
PropValue::Float(number) => {
let _ = write!(out, "{number}");
}
PropValue::Flag(flag) => out.push_str(if *flag { "true" } else { "false" }),
}
}