Skip to content

Commit

Permalink
Add support for disabling ansi color when the feature is enabled (#16)
Browse files Browse the repository at this point in the history
* Add support for disabling ansi color when the feature is enabled

* typo

Co-authored-by: Björn Westlin <[email protected]>

---------

Co-authored-by: Björn Westlin <[email protected]>
  • Loading branch information
fredr and bwestlin authored Aug 5, 2024
1 parent 74a13b4 commit 0305c77
Show file tree
Hide file tree
Showing 3 changed files with 117 additions and 32 deletions.
99 changes: 78 additions & 21 deletions src/formatter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,9 @@ pub struct EventsFormatter {
pub(crate) with_span_path: bool,
pub(crate) with_location: bool,
pub(crate) with_module_path: bool,
pub(crate) with_timestamp: bool,
#[cfg(feature = "ansi_logs")]
pub(crate) with_ansi_color: bool,
}

impl Default for EventsFormatter {
Expand All @@ -52,10 +55,19 @@ impl Default for EventsFormatter {
with_span_path: true,
with_location: false,
with_module_path: false,
with_timestamp: true,
#[cfg(feature = "ansi_logs")]
with_ansi_color: default_enable_ansi_color(),
}
}
}

#[cfg(feature = "ansi_logs")]
fn default_enable_ansi_color() -> bool {
use std::io::IsTerminal;
std::io::stdout().is_terminal()
}

impl<S, N> FormatEvent<S, N> for EventsFormatter
where
S: Subscriber + for<'a> LookupSpan<'a>,
Expand All @@ -67,19 +79,25 @@ where
mut writer: format::Writer<'_>,
event: &Event<'_>,
) -> fmt::Result {
let mut serializer = Serializer::new(&mut writer);
let mut serializer = Serializer::new(
&mut writer,
#[cfg(feature = "ansi_logs")]
self.with_ansi_color,
);

let mut visit = || {
let metadata = event.metadata();

serializer.serialize_key("ts")?;
serializer.writer.write_char('=')?;
time::OffsetDateTime::now_utc()
.format_into(
&mut serializer,
&time::format_description::well_known::Rfc3339,
)
.map_err(|_e| fmt::Error)?;
if self.with_timestamp {
serializer.serialize_key("ts")?;
serializer.writer.write_char('=')?;
time::OffsetDateTime::now_utc()
.format_into(
&mut serializer,
&time::format_description::well_known::Rfc3339,
)
.map_err(|_e| fmt::Error)?;
}

if self.with_level {
let level = match *metadata.level() {
Expand All @@ -92,17 +110,21 @@ where

#[cfg(feature = "ansi_logs")]
{
let level_str = match *metadata.level() {
tracing::Level::ERROR => nu_ansi_term::Color::Red,
tracing::Level::WARN => nu_ansi_term::Color::Yellow,
tracing::Level::INFO => nu_ansi_term::Color::Green,
tracing::Level::DEBUG => nu_ansi_term::Color::Blue,
tracing::Level::TRACE => nu_ansi_term::Color::Purple,
}
.bold()
.paint(level);
if self.with_ansi_color {
let level_str = match *metadata.level() {
tracing::Level::ERROR => nu_ansi_term::Color::Red,
tracing::Level::WARN => nu_ansi_term::Color::Yellow,
tracing::Level::INFO => nu_ansi_term::Color::Green,
tracing::Level::DEBUG => nu_ansi_term::Color::Blue,
tracing::Level::TRACE => nu_ansi_term::Color::Purple,
}
.bold()
.paint(level);

serializer.serialize_entry("level", &level_str.to_string())?;
serializer.serialize_entry("level", &level_str.to_string())?;
} else {
serializer.serialize_entry("level", level)?;
}
}

#[cfg(not(feature = "ansi_logs"))]
Expand Down Expand Up @@ -160,7 +182,11 @@ where
}

let mut span_path = String::with_capacity(required_capacity);
let s = Serializer::new(&mut span_path);
let s = Serializer::new(
&mut span_path,
#[cfg(feature = "ansi_logs")]
self.with_ansi_color,
);
let mut insert_sep = false;
for span in span.scope().from_root() {
if insert_sep {
Expand Down Expand Up @@ -222,7 +248,11 @@ impl<'writer> FormatFields<'writer> for FieldsFormatter {
mut writer: format::Writer<'writer>,
fields: R,
) -> fmt::Result {
let mut serializer = Serializer::new(&mut writer);
let mut serializer = Serializer::new(
&mut writer,
#[cfg(feature = "ansi_logs")]
false,
);
let mut visitor = Visitor::new(&mut serializer);
fields.record(&mut visitor);
Ok(())
Expand Down Expand Up @@ -452,6 +482,33 @@ mod tests {
assert!(content.contains("ts=20"));
}

#[test]
#[cfg(feature = "ansi_logs")]
fn test_disable_ansi_color() {
use tracing::subscriber;

let mock_writer = MockMakeWriter::new();
let subscriber = builder::builder()
// disable timestamp so it can be asserted
.with_timestamp(false)
.with_ansi_color(false)
.subscriber_builder()
.with_writer(mock_writer.clone())
.finish();

subscriber::with_default(subscriber, || {
tracing::info!("message");
});

let content = mock_writer.get_content();

// assert that there is no ansi color sequences
assert_eq!(
content,
"level=info target=tracing_logfmt::formatter::tests message=message\n"
);
}

#[test]
#[cfg(feature = "ansi_logs")]
fn test_span_and_span_path_with_quoting() {
Expand Down
9 changes: 9 additions & 0 deletions src/formatter/builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,15 @@ impl Builder {
self.events.with_module_path = enable;
self
}
pub fn with_timestamp(mut self, enable: bool) -> Self {
self.events.with_timestamp = enable;
self
}
#[cfg(feature = "ansi_logs")]
pub fn with_ansi_color(mut self, enable: bool) -> Self {
self.events.with_ansi_color = enable;
self
}

pub fn layer<S>(self) -> Layer<S, FieldsFormatter, EventsFormatter>
where
Expand Down
41 changes: 30 additions & 11 deletions src/serializer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,17 +16,21 @@ impl From<std::fmt::Error> for SerializerError {
pub(crate) struct Serializer<W> {
pub(crate) writer: W,
writing_first_entry: bool,
#[cfg(feature = "ansi_logs")]
with_ansi_color: bool,
}

impl<W> Serializer<W>
where
W: fmt::Write,
{
#[inline]
pub(crate) fn new(writer: W) -> Self {
pub(crate) fn new(writer: W, #[cfg(feature = "ansi_logs")] with_ansi_color: bool) -> Self {
Serializer {
writer,
writing_first_entry: true,
#[cfg(feature = "ansi_logs")]
with_ansi_color,
}
}

Expand Down Expand Up @@ -98,16 +102,22 @@ where

#[cfg(feature = "ansi_logs")]
{
let mut s = String::new();
for c in chars {
s.push(c);
if self.with_ansi_color {
let mut s = String::new();
for c in chars {
s.push(c);
}
self.writer.write_str(
&nu_ansi_term::Color::Rgb(109, 139, 140)
.bold()
.paint(s)
.to_string(),
)?;
} else {
for c in chars {
self.writer.write_char(c)?;
}
}
self.writer.write_str(
&nu_ansi_term::Color::Rgb(109, 139, 140)
.bold()
.paint(s)
.to_string(),
)?;
}
Ok(())
}
Expand Down Expand Up @@ -215,7 +225,7 @@ mod tests {

for ((k, v), expected_output) in tests {
let mut output = String::new();
let mut s = Serializer::new(&mut output);
let mut s = Serializer::new(&mut output, true);
assert!(s.serialize_entry(k, v).is_ok());
assert_eq!(output, expected_output,);
}
Expand Down Expand Up @@ -261,7 +271,11 @@ mod tests {

for (input, expected_error) in tests {
let mut output = String::new();

#[cfg(not(feature = "ansi_logs"))]
let mut s = Serializer::new(&mut output);
#[cfg(feature = "ansi_logs")]
let mut s = Serializer::new(&mut output, true);
assert_eq!(s.serialize_key(input), Err(expected_error));
}
}
Expand All @@ -286,7 +300,12 @@ mod tests {

for (input, expected_output) in tests {
let mut output = String::new();

#[cfg(not(feature = "ansi_logs"))]
let mut s = Serializer::new(&mut output);
#[cfg(feature = "ansi_logs")]
let mut s = Serializer::new(&mut output, true);

assert!(s.serialize_value(input).is_ok());

assert_eq!(output, expected_output);
Expand Down

0 comments on commit 0305c77

Please sign in to comment.