Skip to content

Commit

Permalink
fix: FastraceEvent should not hardcode layout (#46)
Browse files Browse the repository at this point in the history
  • Loading branch information
andylokandy committed Aug 14, 2024
1 parent cc3db83 commit 56797ca
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 9 deletions.
25 changes: 16 additions & 9 deletions src/append/fastrace.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,26 +12,33 @@
// See the License for the specific language governing permissions and
// limitations under the License.

use std::borrow::Cow;

use jiff::Zoned;
use log::Record;

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

/// An appender that adds log records to fastrace as an event associated to the current span.
#[derive(Default, Debug, Clone)]
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, || {
[
(Cow::from("level"), Cow::from(record.level().as_str())),
(Cow::from("timestamp"), Cow::from(Zoned::now().to_string())),
]
.into_iter()
.chain(
collect_kvs(record.key_values())
.into_iter()
.map(|(k, v)| (Cow::from(k), Cow::from(v))),
)
});
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 56797ca

Please sign in to comment.