Skip to content

Commit 0305c77

Browse files
fredrbwestlin
andauthored
Add support for disabling ansi color when the feature is enabled (#16)
* 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]>
1 parent 74a13b4 commit 0305c77

File tree

3 files changed

+117
-32
lines changed

3 files changed

+117
-32
lines changed

src/formatter.rs

Lines changed: 78 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,9 @@ pub struct EventsFormatter {
4141
pub(crate) with_span_path: bool,
4242
pub(crate) with_location: bool,
4343
pub(crate) with_module_path: bool,
44+
pub(crate) with_timestamp: bool,
45+
#[cfg(feature = "ansi_logs")]
46+
pub(crate) with_ansi_color: bool,
4447
}
4548

4649
impl Default for EventsFormatter {
@@ -52,10 +55,19 @@ impl Default for EventsFormatter {
5255
with_span_path: true,
5356
with_location: false,
5457
with_module_path: false,
58+
with_timestamp: true,
59+
#[cfg(feature = "ansi_logs")]
60+
with_ansi_color: default_enable_ansi_color(),
5561
}
5662
}
5763
}
5864

65+
#[cfg(feature = "ansi_logs")]
66+
fn default_enable_ansi_color() -> bool {
67+
use std::io::IsTerminal;
68+
std::io::stdout().is_terminal()
69+
}
70+
5971
impl<S, N> FormatEvent<S, N> for EventsFormatter
6072
where
6173
S: Subscriber + for<'a> LookupSpan<'a>,
@@ -67,19 +79,25 @@ where
6779
mut writer: format::Writer<'_>,
6880
event: &Event<'_>,
6981
) -> fmt::Result {
70-
let mut serializer = Serializer::new(&mut writer);
82+
let mut serializer = Serializer::new(
83+
&mut writer,
84+
#[cfg(feature = "ansi_logs")]
85+
self.with_ansi_color,
86+
);
7187

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

75-
serializer.serialize_key("ts")?;
76-
serializer.writer.write_char('=')?;
77-
time::OffsetDateTime::now_utc()
78-
.format_into(
79-
&mut serializer,
80-
&time::format_description::well_known::Rfc3339,
81-
)
82-
.map_err(|_e| fmt::Error)?;
91+
if self.with_timestamp {
92+
serializer.serialize_key("ts")?;
93+
serializer.writer.write_char('=')?;
94+
time::OffsetDateTime::now_utc()
95+
.format_into(
96+
&mut serializer,
97+
&time::format_description::well_known::Rfc3339,
98+
)
99+
.map_err(|_e| fmt::Error)?;
100+
}
83101

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

93111
#[cfg(feature = "ansi_logs")]
94112
{
95-
let level_str = match *metadata.level() {
96-
tracing::Level::ERROR => nu_ansi_term::Color::Red,
97-
tracing::Level::WARN => nu_ansi_term::Color::Yellow,
98-
tracing::Level::INFO => nu_ansi_term::Color::Green,
99-
tracing::Level::DEBUG => nu_ansi_term::Color::Blue,
100-
tracing::Level::TRACE => nu_ansi_term::Color::Purple,
101-
}
102-
.bold()
103-
.paint(level);
113+
if self.with_ansi_color {
114+
let level_str = match *metadata.level() {
115+
tracing::Level::ERROR => nu_ansi_term::Color::Red,
116+
tracing::Level::WARN => nu_ansi_term::Color::Yellow,
117+
tracing::Level::INFO => nu_ansi_term::Color::Green,
118+
tracing::Level::DEBUG => nu_ansi_term::Color::Blue,
119+
tracing::Level::TRACE => nu_ansi_term::Color::Purple,
120+
}
121+
.bold()
122+
.paint(level);
104123

105-
serializer.serialize_entry("level", &level_str.to_string())?;
124+
serializer.serialize_entry("level", &level_str.to_string())?;
125+
} else {
126+
serializer.serialize_entry("level", level)?;
127+
}
106128
}
107129

108130
#[cfg(not(feature = "ansi_logs"))]
@@ -160,7 +182,11 @@ where
160182
}
161183

162184
let mut span_path = String::with_capacity(required_capacity);
163-
let s = Serializer::new(&mut span_path);
185+
let s = Serializer::new(
186+
&mut span_path,
187+
#[cfg(feature = "ansi_logs")]
188+
self.with_ansi_color,
189+
);
164190
let mut insert_sep = false;
165191
for span in span.scope().from_root() {
166192
if insert_sep {
@@ -222,7 +248,11 @@ impl<'writer> FormatFields<'writer> for FieldsFormatter {
222248
mut writer: format::Writer<'writer>,
223249
fields: R,
224250
) -> fmt::Result {
225-
let mut serializer = Serializer::new(&mut writer);
251+
let mut serializer = Serializer::new(
252+
&mut writer,
253+
#[cfg(feature = "ansi_logs")]
254+
false,
255+
);
226256
let mut visitor = Visitor::new(&mut serializer);
227257
fields.record(&mut visitor);
228258
Ok(())
@@ -452,6 +482,33 @@ mod tests {
452482
assert!(content.contains("ts=20"));
453483
}
454484

485+
#[test]
486+
#[cfg(feature = "ansi_logs")]
487+
fn test_disable_ansi_color() {
488+
use tracing::subscriber;
489+
490+
let mock_writer = MockMakeWriter::new();
491+
let subscriber = builder::builder()
492+
// disable timestamp so it can be asserted
493+
.with_timestamp(false)
494+
.with_ansi_color(false)
495+
.subscriber_builder()
496+
.with_writer(mock_writer.clone())
497+
.finish();
498+
499+
subscriber::with_default(subscriber, || {
500+
tracing::info!("message");
501+
});
502+
503+
let content = mock_writer.get_content();
504+
505+
// assert that there is no ansi color sequences
506+
assert_eq!(
507+
content,
508+
"level=info target=tracing_logfmt::formatter::tests message=message\n"
509+
);
510+
}
511+
455512
#[test]
456513
#[cfg(feature = "ansi_logs")]
457514
fn test_span_and_span_path_with_quoting() {

src/formatter/builder.rs

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,15 @@ impl Builder {
6161
self.events.with_module_path = enable;
6262
self
6363
}
64+
pub fn with_timestamp(mut self, enable: bool) -> Self {
65+
self.events.with_timestamp = enable;
66+
self
67+
}
68+
#[cfg(feature = "ansi_logs")]
69+
pub fn with_ansi_color(mut self, enable: bool) -> Self {
70+
self.events.with_ansi_color = enable;
71+
self
72+
}
6473

6574
pub fn layer<S>(self) -> Layer<S, FieldsFormatter, EventsFormatter>
6675
where

src/serializer.rs

Lines changed: 30 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -16,17 +16,21 @@ impl From<std::fmt::Error> for SerializerError {
1616
pub(crate) struct Serializer<W> {
1717
pub(crate) writer: W,
1818
writing_first_entry: bool,
19+
#[cfg(feature = "ansi_logs")]
20+
with_ansi_color: bool,
1921
}
2022

2123
impl<W> Serializer<W>
2224
where
2325
W: fmt::Write,
2426
{
2527
#[inline]
26-
pub(crate) fn new(writer: W) -> Self {
28+
pub(crate) fn new(writer: W, #[cfg(feature = "ansi_logs")] with_ansi_color: bool) -> Self {
2729
Serializer {
2830
writer,
2931
writing_first_entry: true,
32+
#[cfg(feature = "ansi_logs")]
33+
with_ansi_color,
3034
}
3135
}
3236

@@ -98,16 +102,22 @@ where
98102

99103
#[cfg(feature = "ansi_logs")]
100104
{
101-
let mut s = String::new();
102-
for c in chars {
103-
s.push(c);
105+
if self.with_ansi_color {
106+
let mut s = String::new();
107+
for c in chars {
108+
s.push(c);
109+
}
110+
self.writer.write_str(
111+
&nu_ansi_term::Color::Rgb(109, 139, 140)
112+
.bold()
113+
.paint(s)
114+
.to_string(),
115+
)?;
116+
} else {
117+
for c in chars {
118+
self.writer.write_char(c)?;
119+
}
104120
}
105-
self.writer.write_str(
106-
&nu_ansi_term::Color::Rgb(109, 139, 140)
107-
.bold()
108-
.paint(s)
109-
.to_string(),
110-
)?;
111121
}
112122
Ok(())
113123
}
@@ -215,7 +225,7 @@ mod tests {
215225

216226
for ((k, v), expected_output) in tests {
217227
let mut output = String::new();
218-
let mut s = Serializer::new(&mut output);
228+
let mut s = Serializer::new(&mut output, true);
219229
assert!(s.serialize_entry(k, v).is_ok());
220230
assert_eq!(output, expected_output,);
221231
}
@@ -261,7 +271,11 @@ mod tests {
261271

262272
for (input, expected_error) in tests {
263273
let mut output = String::new();
274+
275+
#[cfg(not(feature = "ansi_logs"))]
264276
let mut s = Serializer::new(&mut output);
277+
#[cfg(feature = "ansi_logs")]
278+
let mut s = Serializer::new(&mut output, true);
265279
assert_eq!(s.serialize_key(input), Err(expected_error));
266280
}
267281
}
@@ -286,7 +300,12 @@ mod tests {
286300

287301
for (input, expected_output) in tests {
288302
let mut output = String::new();
303+
304+
#[cfg(not(feature = "ansi_logs"))]
289305
let mut s = Serializer::new(&mut output);
306+
#[cfg(feature = "ansi_logs")]
307+
let mut s = Serializer::new(&mut output, true);
308+
290309
assert!(s.serialize_value(input).is_ok());
291310

292311
assert_eq!(output, expected_output);

0 commit comments

Comments
 (0)