Skip to content

Commit f5c5ef9

Browse files
committed
feat: Add support for Key-Value data in log records.
See rust-lang/log#328
1 parent 8f4361b commit f5c5ef9

File tree

5 files changed

+291
-52
lines changed

5 files changed

+291
-52
lines changed

Cargo.lock

Lines changed: 62 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

Cargo.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,7 @@ color = ["dep:anstream", "dep:anstyle"]
5252
auto-color = ["color", "anstream/auto"]
5353
humantime = ["dep:humantime"]
5454
regex = ["env_filter/regex"]
55+
unstable-kv = ["log/kv_unstable"]
5556

5657
[dependencies]
5758
log = { version = "0.4.8", features = ["std"] }

src/fmt/kv.rs

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
use std::io::{self, Write};
2+
3+
use super::Formatter;
4+
use log::kv::{source::Source, Error, Key, Value, Visitor};
5+
6+
/// Format function for serializing key/value pairs
7+
///
8+
/// This function determines how key/value pairs for structured logs are serialized within the default
9+
/// format.
10+
pub(crate) type KvFormatFn = dyn Fn(&mut Formatter, &dyn Source) -> io::Result<()> + Sync + Send;
11+
12+
/// Null Key Value Format
13+
///
14+
/// This function is intended to be passed to
15+
/// [`Builder::format_key_values`](crate::Builder::format_key_values).
16+
///
17+
/// This key value format simply ignores any key/value fields and doesn't include them in the
18+
/// output.
19+
pub fn hidden_kv_format(_formatter: &mut Formatter, _fields: &dyn Source) -> io::Result<()> {
20+
Ok(())
21+
}
22+
23+
/// Defualt Key Value Format
24+
///
25+
/// This function is intended to be passed to
26+
/// [`Builder::format_key_values`](crate::Builder::format_key_values).
27+
///
28+
/// This is the default key/value format. Which uses an "=" as the separator between the key and
29+
/// value and a " " between each pair.
30+
///
31+
/// For example: `ip=127.0.0.1 port=123456 path=/example`
32+
pub fn default_kv_format(formatter: &mut Formatter, fields: &dyn Source) -> io::Result<()> {
33+
fields
34+
.visit(&mut DefaultVisitor(formatter))
35+
.map_err(|e| io::Error::new(io::ErrorKind::Other, e))
36+
}
37+
38+
struct DefaultVisitor<'a>(&'a mut Formatter);
39+
40+
impl<'a, 'kvs> Visitor<'kvs> for DefaultVisitor<'a> {
41+
fn visit_pair(&mut self, key: Key, value: Value<'kvs>) -> Result<(), Error> {
42+
// TODO: add styling
43+
// tracing-subscriber uses italic for the key and dimmed for the =
44+
write!(self.0, " {}={}", key, value)?;
45+
Ok(())
46+
}
47+
}

0 commit comments

Comments
 (0)