From d2411569fe0125d89d95b3dc71696beae5b6cccb Mon Sep 17 00:00:00 2001 From: dev0 Date: Sun, 10 Sep 2023 05:02:34 +1000 Subject: [PATCH] log formatting --- clash_lib/src/app/logging.rs | 57 ++++++++++++++++++++++++++++++++++-- 1 file changed, 54 insertions(+), 3 deletions(-) diff --git a/clash_lib/src/app/logging.rs b/clash_lib/src/app/logging.rs index 41117973..140371ee 100644 --- a/clash_lib/src/app/logging.rs +++ b/clash_lib/src/app/logging.rs @@ -23,7 +23,9 @@ impl From for filter::LevelFilter { #[derive(Clone, Serialize)] pub struct LogEvent { + #[serde(rename = "type")] pub level: LogLevel, + #[serde(rename = "payload")] pub msg: String, } @@ -44,8 +46,9 @@ where event: &tracing::Event<'_>, _ctx: tracing_subscriber::layer::Context<'_, S>, ) { - // TODO: format log here - let msg = format!("{}", event.metadata().name()); + let mut strs = vec![]; + event.record(&mut EventVisitor(&mut strs)); + let event = LogEvent { level: match event.metadata().level() { &tracing::Level::ERROR => LogLevel::Error, @@ -54,7 +57,7 @@ where &tracing::Level::DEBUG => LogLevel::Debug, &tracing::Level::TRACE => LogLevel::Debug, }, - msg, + msg: strs.join(" "), }; for tx in &self.0 { _ = tx.send(event.clone()); @@ -87,3 +90,51 @@ pub fn setup_logging(level: LogLevel, collector: EventCollector) -> anyhow::Resu tracing::subscriber::set_global_default(subscriber) .map_err(|x| anyhow!("setup logging error: {}", x)) } + +struct EventVisitor<'a>(&'a mut Vec); + +impl<'a> tracing::field::Visit for EventVisitor<'a> { + fn record_bool(&mut self, field: &tracing::field::Field, value: bool) { + println!("bool {} = {}", field.name(), value); + } + + fn record_i64(&mut self, field: &tracing::field::Field, value: i64) { + println!("i64 {} = {}", field.name(), value); + } + + fn record_u64(&mut self, field: &tracing::field::Field, value: u64) { + println!("u64 {} = {}", field.name(), value); + } + + fn record_str(&mut self, field: &tracing::field::Field, value: &str) { + println!("str {} = {}", field.name(), value); + } + + fn record_debug(&mut self, field: &tracing::field::Field, value: &dyn std::fmt::Debug) { + if field.name() == "message" { + self.0.push(format!("{:?}", value)); + } else { + println!("debug {} = {:?}", field.name(), value); + } + } + + fn record_f64(&mut self, field: &tracing::field::Field, value: f64) { + println!("f64 {} = {}", field.name(), value); + } + + fn record_u128(&mut self, field: &tracing::field::Field, value: u128) { + println!("u128 {} = {}", field.name(), value); + } + + fn record_i128(&mut self, field: &tracing::field::Field, value: i128) { + println!("i128 {} = {}", field.name(), value); + } + + fn record_error( + &mut self, + field: &tracing::field::Field, + value: &(dyn std::error::Error + 'static), + ) { + println!("error {} = {}", field.name(), value); + } +}