From c61fbf71a4c6a3c841ba47f09b5025b30cfaa64b Mon Sep 17 00:00:00 2001 From: Mac L Date: Tue, 23 Nov 2021 07:06:22 +0000 Subject: [PATCH] Ensure consistent log formatting (#2819) ## Issue Addressed N/A ## Proposed Changes Filter out certain ascii characters when logging to ensure proper log formatting. --- common/logging/src/lib.rs | 34 +++++++++++++++++++++++++++++++--- 1 file changed, 31 insertions(+), 3 deletions(-) diff --git a/common/logging/src/lib.rs b/common/logging/src/lib.rs index 06c121210..6cbf7e00b 100644 --- a/common/logging/src/lib.rs +++ b/common/logging/src/lib.rs @@ -80,10 +80,8 @@ impl<'a> AlignedRecordDecorator<'a> { message_width, } } -} -impl<'a> Write for AlignedRecordDecorator<'a> { - fn write(&mut self, buf: &[u8]) -> Result { + fn filtered_write(&mut self, buf: &[u8]) -> Result { if self.ignore_comma { //don't write comma self.ignore_comma = false; @@ -97,6 +95,21 @@ impl<'a> Write for AlignedRecordDecorator<'a> { self.wrapped.write(buf) } } +} + +impl<'a> Write for AlignedRecordDecorator<'a> { + fn write(&mut self, buf: &[u8]) -> Result { + if buf.iter().any(|c| is_ascii_control(c)) { + let filtered = buf + .iter() + .cloned() + .map(|c| if !is_ascii_control(&c) { c } else { b'_' }) + .collect::>(); + self.filtered_write(&filtered) + } else { + self.filtered_write(buf) + } + } fn flush(&mut self) -> Result<()> { self.wrapped.flush() @@ -159,6 +172,21 @@ impl<'a> slog_term::RecordDecorator for AlignedRecordDecorator<'a> { } } +/// Function to filter out ascii control codes. +/// +/// This helps to keep log formatting consistent. +/// Whitespace and padding control codes are excluded. +fn is_ascii_control(character: &u8) -> bool { + matches!( + character, + b'\x00'..=b'\x08' | + b'\x0b'..=b'\x0c' | + b'\x0e'..=b'\x1f' | + b'\x7f' | + b'\x81'..=b'\x9f' + ) +} + /// Return a logger suitable for test usage. /// /// By default no logs will be printed, but they can be enabled via