diff --git a/CHANGELOG.md b/CHANGELOG.md index 11c0ffd..8dfc507 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,7 +5,7 @@ # Change Log ## 0.9.22 - +- Fixed an issue in server logging where the large allocations could be made by debug prints even at lower debug levels ## 0.9.21 - The DLS will now properly not report conflicts between statements in a `#if` and its corresponding `#else` branch diff --git a/src/logging.rs b/src/logging.rs index a88943c..0e0a929 100644 --- a/src/logging.rs +++ b/src/logging.rs @@ -2,6 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 and MIT use std::io::Write; +use std::fmt; use std::sync::LazyLock; use chrono::Local; @@ -52,22 +53,55 @@ pub static MAX_LOG_MESSAGE_LENGTH: LazyLock> = #[macro_export] macro_rules! format_truncated { ($trunc_len:expr, $($arg:tt)*) => {{ - let s = format!($($arg)*); - 'check_block: { - if let Some(max_len) = $trunc_len { - if max_len > 0 && s.len() > max_len { - let mut slice_index = max_len; - while !s.is_char_boundary(slice_index) { - slice_index -= 1; - } - break 'check_block [&s[..slice_index], " ..."].concat(); - } - } - s - } + $crate::logging::format_truncated($trunc_len, format_args!($($arg)*)) }}; } +struct TruncatedWriter { + output: String, + max_len: usize, + truncated: bool, +} + +impl fmt::Write for TruncatedWriter { + fn write_str(&mut self, value: &str) -> fmt::Result { + if self.truncated { + return Err(fmt::Error); + } + let remaining = self.max_len - self.output.len(); + if value.len() <= remaining { + self.output.push_str(value); + return Ok(()); + } + let mut end = remaining; + while !value.is_char_boundary(end) { + end -= 1; + } + self.output.push_str(&value[..end]); + self.truncated = true; + // Stop recursive Debug/Display formatting as soon as the limit is exceeded. + Err(fmt::Error) + } +} + +pub fn format_truncated(max_len: Option, args: fmt::Arguments<'_>) -> String { + let Some(max_len) = max_len.filter(|length|*length > 0) else { + return fmt::format(args); + }; + let mut writer = TruncatedWriter { + output: String::new(), + max_len, + truncated: false, + }; + if fmt::write(&mut writer, args).is_err() && !writer.truncated { + panic!("a formatting trait implementation returned an error while formatting a log message"); + } + if writer.truncated { + writer.output.push_str(" ..."); + } + writer.output +} + pub fn init() { // Slightly dumb way to do this, build the logger once with defaults // to get the max level for all modules from env, then build again @@ -112,6 +146,8 @@ pub fn set_global_log_level(level: log::LevelFilter) { #[cfg(test)] mod tests { + use std::fmt; + #[test] fn test_format_truncated() { let s = format_truncated!(Some(5), "Hello, world!"); @@ -120,6 +156,8 @@ mod tests { assert_eq!(s, "Hello, world!"); let s = format_truncated!(None, "Hello, world!"); assert_eq!(s, "Hello, world!"); + let s = format_truncated!(Some(0), "Hello, world!"); + assert_eq!(s, "Hello, world!"); } #[test] @@ -134,4 +172,63 @@ mod tests { let s = format_truncated!(Some(30), "πŸ˜€πŸ˜€πŸ˜€πŸ˜€πŸ˜€"); assert_eq!(s, "πŸ˜€πŸ˜€πŸ˜€πŸ˜€πŸ˜€"); } + + #[test] + fn formatting_options_are_preserved() { + let value = 42; + let expected = format!("{value:08x} {number:>6.2} {:#?}", [1, 2], number = 1.25); + assert_eq!(format_truncated!(Some(expected.len()), + "{value:08x} {number:>6.2} {:#?}", [1, 2], number = 1.25), expected); + assert_eq!(format_truncated!(Some(5), "{value:08x}"), "00000 ..."); + } + + #[test] + fn truncation_stops_formatting() { + struct TooLong; + impl fmt::Display for TooLong { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter.write_str("12345")?; + formatter.write_str("6")?; + panic!("formatting should have stopped"); + } + } + assert_eq!(format_truncated!(Some(5), "{TooLong}"), "12345 ..."); + } + + #[test] + fn debug_collections_stop_visiting_elements_at_the_limit() { + use std::cell::Cell; + + struct Counted<'a>(&'a Cell); + impl fmt::Debug for Counted<'_> { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + self.0.set(self.0.get() + 1); + formatter.write_str("entry") + } + } + let visits = Cell::new(0); + let entries: Vec<_> = (0..10_000).map(|_|Counted(&visits)).collect(); + let result = format_truncated!(Some(10), "{entries:?}"); + assert_eq!(result, "[entry, en ..."); + assert_eq!(visits.get(), 2); + } + + #[test] + fn unicode_truncation_across_writes() { + assert_eq!(format_truncated!(Some(5), "{}{}", "abc", "πŸ˜€def"), "abc ..."); + assert_eq!(format_truncated!(Some(4), "{}{}", "abcd", ""), "abcd"); + assert_eq!(format_truncated!(Some(1), "πŸ˜€"), " ..."); + } + + #[test] + #[should_panic(expected = "formatting trait implementation returned an error")] + fn formatter_errors_are_not_silenced() { + struct Broken; + impl fmt::Display for Broken { + fn fmt(&self, _: &mut fmt::Formatter<'_>) -> fmt::Result { + Err(fmt::Error) + } + } + let _ = format_truncated!(Some(5), "{Broken}"); + } }