Skip to content

Commit

Permalink
feat(kv): Add styling for key in default format
Browse files Browse the repository at this point in the history
Make the key italic by default.
  • Loading branch information
tmccombs committed Jan 29, 2024
1 parent e8c94bc commit 29e378d
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 2 deletions.
3 changes: 3 additions & 0 deletions examples/direct_logger.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ use env_logger::{Builder, WriteStyle};

use log::{Level, LevelFilter, Log, MetadataBuilder, Record};

static kvs: (&str, &str) = ("test", "something");

Check failure

Code scanning / clippy

static variable kvs should have an upper case name Error

static variable kvs should have an upper case name

fn record() -> Record<'static> {
let error_metadata = MetadataBuilder::new()
.target("myApp")
Expand All @@ -20,6 +22,7 @@ fn record() -> Record<'static> {
.line(Some(433))
.file(Some("app.rs"))
.module_path(Some("server"))
.key_values(&kvs)
.build()
}

Expand Down
25 changes: 23 additions & 2 deletions src/fmt/kv.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use std::io::{self, Write};

use super::Formatter;
use super::{Formatter, StyledValue, WriteStyle};
use anstyle::Style;
use log::kv::{source::Source, Error, Key, Value, Visitor};

/// Format function for serializing key/value pairs
Expand Down Expand Up @@ -41,7 +42,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<Key<'k>> {
#[cfg(feature = "color")]
{
StyledValue {
style: if self.0.write_style == WriteStyle::Never {
Style::new()
} else {
Style::new().italic()
},
value: text,
}
}
#[cfg(not(feature = "color"))]
{
key
}
}
}
3 changes: 3 additions & 0 deletions src/fmt/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -292,6 +292,9 @@ impl<T: std::fmt::Display> std::fmt::Display for StyledValue<T> {
}
}

#[cfg(not(feature = "color"))]
type StyledValue<T> = T;

/// The default format.
///
/// This format needs to work with any combination of crate features.
Expand Down

0 comments on commit 29e378d

Please sign in to comment.