Skip to content

Commit

Permalink
log formatting
Browse files Browse the repository at this point in the history
  • Loading branch information
ibigbug committed Sep 9, 2023
1 parent fb71518 commit d241156
Showing 1 changed file with 54 additions and 3 deletions.
57 changes: 54 additions & 3 deletions clash_lib/src/app/logging.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,9 @@ impl From<LogLevel> for filter::LevelFilter {

#[derive(Clone, Serialize)]
pub struct LogEvent {
#[serde(rename = "type")]
pub level: LogLevel,
#[serde(rename = "payload")]
pub msg: String,
}

Expand All @@ -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,
Expand All @@ -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());
Expand Down Expand Up @@ -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<String>);

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);
}
}

0 comments on commit d241156

Please sign in to comment.