diff --git a/examples/direct_logger.rs b/examples/direct_logger.rs index 4d7f39d..397ccd8 100644 --- a/examples/direct_logger.rs +++ b/examples/direct_logger.rs @@ -8,19 +8,27 @@ use env_logger::{Builder, WriteStyle}; use log::{Level, LevelFilter, Log, MetadataBuilder, Record}; +#[cfg(feature = "unstable-kv")] +static KVS: (&str, &str) = ("test", "something"); + fn record() -> Record<'static> { let error_metadata = MetadataBuilder::new() .target("myApp") .level(Level::Error) .build(); - Record::builder() + let mut builder = Record::builder(); + builder .metadata(error_metadata) .args(format_args!("Error!")) .line(Some(433)) .file(Some("app.rs")) - .module_path(Some("server")) - .build() + .module_path(Some("server")); + #[cfg(feature = "unstable-kv")] + { + builder.key_values(&KVS); + } + builder.build() } fn main() { diff --git a/src/fmt/kv.rs b/src/fmt/kv.rs index bd2cae3..cc8cf4d 100644 --- a/src/fmt/kv.rs +++ b/src/fmt/kv.rs @@ -1,6 +1,10 @@ use std::io::{self, Write}; -use super::Formatter; +#[cfg(feature = "color")] +use super::WriteStyle; +use super::{Formatter, StyledValue}; +#[cfg(feature = "color")] +use anstyle::Style; use log::kv::{source::Source, Error, Key, Value, Visitor}; /// Format function for serializing key/value pairs @@ -41,7 +45,27 @@ impl<'a, 'kvs> Visitor<'kvs> for DefaultVisitor<'a> { fn visit_pair(&mut self, key: Key, value: Value<'kvs>) -> Result<(), Error> { // TODO: add styling // tracing-subscriber uses italic for the key and dimmed for the = - write!(self.0, " {}={}", key, value)?; + write!(self.0, " {}={}", self.style_key(key), value)?; Ok(()) } } + +impl DefaultVisitor<'_> { + fn style_key<'k>(&self, text: Key<'k>) -> StyledValue> { + #[cfg(feature = "color")] + { + StyledValue { + style: if self.0.write_style == WriteStyle::Never { + Style::new() + } else { + Style::new().italic() + }, + value: text, + } + } + #[cfg(not(feature = "color"))] + { + text + } + } +} diff --git a/src/fmt/mod.rs b/src/fmt/mod.rs index b7472e3..cbacc44 100644 --- a/src/fmt/mod.rs +++ b/src/fmt/mod.rs @@ -292,6 +292,9 @@ impl std::fmt::Display for StyledValue { } } +#[cfg(not(feature = "color"))] +type StyledValue = T; + /// The default format. /// /// This format needs to work with any combination of crate features. diff --git a/src/logger.rs b/src/logger.rs index 509c299..ccc3615 100644 --- a/src/logger.rs +++ b/src/logger.rs @@ -321,7 +321,7 @@ impl Builder { /// The format function is expected to output the string directly to the `Formatter` so that /// implementations can use the [`std::fmt`] macros, similar to the main format function. /// - /// The default format uses a space to separte each key-value pair, with an "=" between + /// The default format uses a space to separate each key-value pair, with an "=" between /// the key and value. #[cfg(feature = "unstable-kv")] pub fn format_key_values(&mut self, format: F) -> &mut Self