use crate::logging::fast_local_time::FastLocalTime;
use ansi_term::Colour;
use regex::Regex;
use std::fmt::{self, Write};
use tracing::{Event, Level, Subscriber};
use tracing_log::NormalizeEvent;
use tracing_subscriber::{
field::RecordFields,
fmt::{time::FormatTime, FmtContext, FormatEvent, FormatFields},
layer::Context,
registry::{LookupSpan, SpanRef},
};
pub struct EventFormat<T = FastLocalTime> {
pub timer: T,
pub display_target: bool,
pub display_level: bool,
pub display_thread_name: bool,
pub enable_color: bool,
pub dup_to_stdout: bool,
}
impl<T> EventFormat<T>
where
T: FormatTime,
{
pub(crate) fn format_event_custom<'b, S, N>(
&self,
ctx: CustomFmtContext<'b, S, N>,
writer: &mut dyn fmt::Write,
event: &Event,
) -> fmt::Result
where
S: Subscriber + for<'a> LookupSpan<'a>,
N: for<'a> FormatFields<'a> + 'static,
{
let writer = &mut ControlCodeSanitizer::new(!self.enable_color, writer);
let normalized_meta = event.normalized_metadata();
let meta = normalized_meta.as_ref().unwrap_or_else(|| event.metadata());
time::write(&self.timer, writer, self.enable_color)?;
if self.display_level {
let fmt_level = { FmtLevel::new(meta.level(), self.enable_color) };
write!(writer, "{} ", fmt_level)?;
}
if self.display_thread_name {
let current_thread = std::thread::current();
match current_thread.name() {
Some(name) => {
write!(writer, "{} ", FmtThreadName::new(name))?;
},
None => {
write!(writer, "{:0>2?} ", current_thread.id())?;
},
}
}
if self.display_target {
write!(writer, "{}: ", meta.target())?;
}
if let Some(span) = ctx.lookup_current() {
for span in span.scope() {
let exts = span.extensions();
if let Some(prefix) = exts.get::<super::layers::Prefix>() {
write!(writer, "{}", prefix.as_str())?;
break
}
}
}
if !writer.sanitize {
writer.flush()?;
writer.sanitize = true;
}
ctx.format_fields(writer, event)?;
writeln!(writer)?;
writer.flush()
}
}
impl<S, N, T> FormatEvent<S, N> for EventFormat<T>
where
S: Subscriber + for<'a> LookupSpan<'a>,
N: for<'a> FormatFields<'a> + 'static,
T: FormatTime,
{
fn format_event(
&self,
ctx: &FmtContext<S, N>,
writer: &mut dyn fmt::Write,
event: &Event,
) -> fmt::Result {
if self.dup_to_stdout &&
(event.metadata().level() == &Level::INFO ||
event.metadata().level() == &Level::WARN ||
event.metadata().level() == &Level::ERROR)
{
let mut out = String::new();
self.format_event_custom(CustomFmtContext::FmtContext(ctx), &mut out, event)?;
writer.write_str(&out)?;
print!("{}", out);
Ok(())
} else {
self.format_event_custom(CustomFmtContext::FmtContext(ctx), writer, event)
}
}
}
struct FmtLevel<'a> {
level: &'a Level,
ansi: bool,
}
impl<'a> FmtLevel<'a> {
pub(crate) fn new(level: &'a Level, ansi: bool) -> Self {
Self { level, ansi }
}
}
const TRACE_STR: &str = "TRACE";
const DEBUG_STR: &str = "DEBUG";
const INFO_STR: &str = " INFO";
const WARN_STR: &str = " WARN";
const ERROR_STR: &str = "ERROR";
impl<'a> fmt::Display for FmtLevel<'a> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if self.ansi {
match *self.level {
Level::TRACE => write!(f, "{}", Colour::Purple.paint(TRACE_STR)),
Level::DEBUG => write!(f, "{}", Colour::Blue.paint(DEBUG_STR)),
Level::INFO => write!(f, "{}", Colour::Green.paint(INFO_STR)),
Level::WARN => write!(f, "{}", Colour::Yellow.paint(WARN_STR)),
Level::ERROR => write!(f, "{}", Colour::Red.paint(ERROR_STR)),
}
} else {
match *self.level {
Level::TRACE => f.pad(TRACE_STR),
Level::DEBUG => f.pad(DEBUG_STR),
Level::INFO => f.pad(INFO_STR),
Level::WARN => f.pad(WARN_STR),
Level::ERROR => f.pad(ERROR_STR),
}
}
}
}
struct FmtThreadName<'a> {
name: &'a str,
}
impl<'a> FmtThreadName<'a> {
pub(crate) fn new(name: &'a str) -> Self {
Self { name }
}
}
impl<'a> fmt::Display for FmtThreadName<'a> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
use std::sync::atomic::{
AtomicUsize,
Ordering::{AcqRel, Acquire, Relaxed},
};
static MAX_LEN: AtomicUsize = AtomicUsize::new(0);
let len = self.name.len();
let mut max_len = MAX_LEN.load(Relaxed);
while len > max_len {
match MAX_LEN.compare_exchange(max_len, len, AcqRel, Acquire) {
Ok(_) => break,
Err(actual) => max_len = actual,
}
}
write!(f, "{:>width$}", self.name, width = max_len)
}
}
mod time {
use ansi_term::Style;
use std::fmt;
use tracing_subscriber::fmt::time::FormatTime;
pub(crate) fn write<T>(timer: T, writer: &mut dyn fmt::Write, with_ansi: bool) -> fmt::Result
where
T: FormatTime,
{
if with_ansi {
let style = Style::new().dimmed();
write!(writer, "{}", style.prefix())?;
timer.format_time(writer)?;
write!(writer, "{}", style.suffix())?;
} else {
timer.format_time(writer)?;
}
writer.write_char(' ')?;
Ok(())
}
}
#[allow(dead_code)]
pub(crate) enum CustomFmtContext<'a, S, N> {
FmtContext(&'a FmtContext<'a, S, N>),
ContextWithFormatFields(&'a Context<'a, S>, &'a N),
}
impl<'a, S, N> FormatFields<'a> for CustomFmtContext<'a, S, N>
where
S: Subscriber + for<'lookup> LookupSpan<'lookup>,
N: for<'writer> FormatFields<'writer> + 'static,
{
fn format_fields<R: RecordFields>(
&self,
writer: &'a mut dyn fmt::Write,
fields: R,
) -> fmt::Result {
match self {
CustomFmtContext::FmtContext(fmt_ctx) => fmt_ctx.format_fields(writer, fields),
CustomFmtContext::ContextWithFormatFields(_ctx, fmt_fields) =>
fmt_fields.format_fields(writer, fields),
}
}
}
impl<'a, S, N> CustomFmtContext<'a, S, N>
where
S: Subscriber + for<'lookup> LookupSpan<'lookup>,
N: for<'writer> FormatFields<'writer> + 'static,
{
#[inline]
pub fn lookup_current(&self) -> Option<SpanRef<'_, S>>
where
S: for<'lookup> LookupSpan<'lookup>,
{
match self {
CustomFmtContext::FmtContext(fmt_ctx) => fmt_ctx.lookup_current(),
CustomFmtContext::ContextWithFormatFields(ctx, _) => ctx.lookup_current(),
}
}
}
struct ControlCodeSanitizer<'a> {
sanitize: bool,
buffer: String,
inner_writer: &'a mut dyn fmt::Write,
}
impl<'a> fmt::Write for ControlCodeSanitizer<'a> {
fn write_str(&mut self, buf: &str) -> fmt::Result {
self.buffer.push_str(buf);
Ok(())
}
}
fn strip_control_codes(input: &str) -> std::borrow::Cow<str> {
lazy_static::lazy_static! {
static ref RE: Regex = Regex::new(r#"(?x)
\x1b\[[^m]+m| # VT100 escape codes
[
\x00-\x09\x0B-\x1F # ASCII control codes / Unicode C0 control codes, except \n
\x7F # ASCII delete
\u{80}-\u{9F} # Unicode C1 control codes
\u{202A}-\u{202E} # Unicode left-to-right / right-to-left control characters
\u{2066}-\u{2069} # Same as above
]
"#).expect("regex parsing doesn't fail; qed");
}
RE.replace_all(input, "")
}
impl<'a> ControlCodeSanitizer<'a> {
fn new(sanitize: bool, inner_writer: &'a mut dyn fmt::Write) -> Self {
Self { sanitize, inner_writer, buffer: String::new() }
}
fn flush(&mut self) -> fmt::Result {
if self.sanitize {
let replaced = strip_control_codes(&self.buffer);
self.inner_writer.write_str(&replaced)?
} else {
self.inner_writer.write_str(&self.buffer)?
}
self.buffer.clear();
Ok(())
}
}