Skip to content

Commit

Permalink
fix: FastraceEvent should not hardcode layout
Browse files Browse the repository at this point in the history
  • Loading branch information
andylokandy committed Aug 14, 2024
1 parent a434e9e commit 24d0bd8
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 8 deletions.
14 changes: 6 additions & 8 deletions src/append/fastrace.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ use jiff::Zoned;
use log::Record;

use crate::append::Append;
use crate::layout::collect_kvs;
use crate::layout::KvDisplay;

/// An appender that adds log records to fastrace as an event associated to the current span.
Expand All @@ -24,14 +25,11 @@ pub struct FastraceEvent;

impl Append for FastraceEvent {
fn append(&self, record: &Record) -> anyhow::Result<()> {
let message = format!(
"{} {:>5} {}{}",
Zoned::now(),
record.level(),
record.args(),
KvDisplay::new(record.key_values()),
);
fastrace::Event::add_to_local_parent(message, || []);
let message = format!("{}", record.args(),);
fastrace::Event::add_to_local_parent(message, || {
[("level", record.level()), ("timestamp", Zoned::now())]
.chain(collect_kvs(record.key_values()))
});
Ok(())
}

Expand Down
22 changes: 22 additions & 0 deletions src/layout/kv.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,3 +45,25 @@ impl<'a, 'kvs> log::kv::Visitor<'kvs> for KvWriter<'a, 'kvs> {
Ok(())
}
}

/// A helper to collect log's key-value pairs.
pub fn collect_kvs(kv: &dyn log::kv::Source) -> Vec<(String, String)> {
let mut collector = KvCollector { kv: Vec::new() };
kv.visit(&mut collector).ok();
collector.kv
}

struct KvCollector {
kv: Vec<(String, String)>,
}

impl<'kvs> log::kv::Visitor<'kvs> for KvCollector {
fn visit_pair(
&mut self,
key: log::kv::Key<'kvs>,
value: log::kv::Value<'kvs>,
) -> Result<(), log::kv::Error> {
self.kv.push((key.to_string(), value.to_string()));
Ok(())
}
}
1 change: 1 addition & 0 deletions src/layout/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ pub use custom::CustomLayout;
pub use identical::IdenticalLayout;
#[cfg(feature = "json")]
pub use json::JsonLayout;
pub use kv::collect_kvs;
pub use kv::KvDisplay;
pub use text::LevelColor;
pub use text::TextLayout;
Expand Down

0 comments on commit 24d0bd8

Please sign in to comment.