Debian Codegraph @

src/fmt/kv.rs

raw symbols SCIP
1 use std::io::{self, Write};
2
3 #[cfg(feature = "color")]
4 use super::WriteStyle;
5 use super::{Formatter, StyledValue};
6 #[cfg(feature = "color")]
7 use anstyle::Style;
8 use log::kv::{Error, Key, Source, Value, VisitSource};
9
10 /// Format function for serializing key/value pairs
11 ///
12 /// This function determines how key/value pairs for structured logs are serialized within the default
13 /// format.
14 pub(crate) type KvFormatFn = dyn Fn(&mut Formatter, &dyn Source) -> io::Result<()> + Sync + Send;
15
16 /// Null Key Value Format
17 ///
18 /// This function is intended to be passed to
19 /// [`Builder::format_key_values`](crate::Builder::format_key_values).
20 ///
21 /// This key value format simply ignores any key/value fields and doesn't include them in the
22 /// output.
23 pub fn hidden_kv_format(_formatter: &mut Formatter, _fields: &dyn Source) -> io::Result<()> {
24 Ok(())
25 }
26
27 /// Default Key Value Format
28 ///
29 /// This function is intended to be passed to
30 /// [`Builder::format_key_values`](crate::Builder::format_key_values).
31 ///
32 /// This is the default key/value format. Which uses an "=" as the separator between the key and
33 /// value and a " " between each pair.
34 ///
35 /// For example: `ip=127.0.0.1 port=123456 path=/example`
36 pub fn default_kv_format(formatter: &mut Formatter, fields: &dyn Source) -> io::Result<()> {
37 fields
38 .visit(&mut DefaultVisitSource(formatter))
39 .map_err(|e| io::Error::new(io::ErrorKind::Other, e))
40 }
41
42 struct DefaultVisitSource<'a>(&'a mut Formatter);
43
44 impl<'kvs> VisitSource<'kvs> for DefaultVisitSource<'_> {
45 fn visit_pair(&mut self, key: Key<'_>, value: Value<'kvs>) -> Result<(), Error> {
46 write!(self.0, " {}={}", self.style_key(key), value)?;
47 Ok(())
48 }
49 }
50
51 impl DefaultVisitSource<'_> {
52 fn style_key<'k>(&self, text: Key<'k>) -> StyledValue<Key<'k>> {
53 #[cfg(feature = "color")]
54 {
55 StyledValue {
56 style: if self.0.write_style == WriteStyle::Never {
57 Style::new()
58 } else {
59 Style::new().italic()
60 },
61 value: text,
62 }
63 }
64 #[cfg(not(feature = "color"))]
65 {
66 text
67 }
68 }
69 }