|
| 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