Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: FastraceEvent should not hardcode layout #46

Merged
merged 3 commits into from
Aug 14, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 16 additions & 9 deletions src/append/fastrace.rs
Original file line number Diff line number Diff line change
@@ -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(())
}

22 changes: 22 additions & 0 deletions src/layout/kv.rs
Original file line number Diff line number Diff line change
@@ -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
@@ -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;