Skip to content

Commit

Permalink
subscriber: fix excessive padding on log messages
Browse files Browse the repository at this point in the history
Don't add padding to `log.*` attributes (from `log` events) which are
not outputted.

## Problem
For example this config which automatically transforms `log`-events to
`tracing` ones:

```rust
tracing_subscriber::fmt()
    .with_max_level(tracing::Level::TRACE)
    .init();
```

With the following log message:

```rust
log::debug!("this is a log line");
```

Prints something like:
"this is a log line   \n"

## Solution
Do something like in the PrettyVisitor: add a write helper which
automatically pads every write.
  • Loading branch information
kaffarell committed Sep 3, 2024
1 parent 527b4f6 commit 808faf6
Showing 1 changed file with 13 additions and 14 deletions.
27 changes: 13 additions & 14 deletions tracing-subscriber/src/fmt/format/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1193,12 +1193,14 @@ impl<'a> DefaultVisitor<'a> {
}
}

fn maybe_pad(&mut self) {
if self.is_empty {
fn write_padded(&mut self, value: &(impl fmt::Debug + ?Sized)) {
let padding = if self.is_empty {
self.is_empty = false;
""
} else {
self.result = write!(self.writer, " ");
}
" "
};
self.result = write!(self.writer, "{}{:?}", padding, value);
}
}

Expand Down Expand Up @@ -1239,26 +1241,23 @@ impl<'a> field::Visit for DefaultVisitor<'a> {
return;
}

self.maybe_pad();
self.result = match field.name() {
"message" => write!(self.writer, "{:?}", value),
match field.name() {
"message" => self.write_padded(value),
// Skip fields that are actually log metadata that have already been handled
#[cfg(feature = "tracing-log")]
name if name.starts_with("log.") => Ok(()),
name if name.starts_with("r#") => write!(
self.writer,
name if name.starts_with("log.") => self.result = Ok(()),
name if name.starts_with("r#") => self.write_padded(&format_args!(
"{}{}{:?}",
self.writer.italic().paint(&name[2..]),
self.writer.dimmed().paint("="),
value
),
name => write!(
self.writer,
)),
name => self.write_padded(&format_args!(
"{}{}{:?}",
self.writer.italic().paint(name),
self.writer.dimmed().paint("="),
value
),
)),
};
}
}
Expand Down

0 comments on commit 808faf6

Please sign in to comment.