From e447bb062e9984c42628dbcc9125c7c9a158a2dd Mon Sep 17 00:00:00 2001 From: tison Date: Tue, 1 Dec 2026 23:15:35 +0800 Subject: [PATCH] fix(layout): omit message separator space when payload is empty Avoid leaving an extra space in `PlainTextLayout` and `TextLayout` when `Record::payload()` produces zero bytes by popping the separator space from the output buffer when nothing was written for the message segment. Signed-off-by: tison --- CHANGELOG.md | 2 +- core/src/layout/plain_text.rs | 8 +++- layouts/text/src/lib.rs | 8 +++- .../tests/core_test/record_and_layout.rs | 28 ++++++++++++++ tests-integration/tests/layout_test/text.rs | 38 +++++++++++++++++++ 5 files changed, 79 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 834db98..6515914 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -93,7 +93,7 @@ All significant changes to this project will be documented in this file. * `ValueView`'s `Display` implementation in `logforth-core` now formats list and map entries as values and string keys instead of exposing internal enum and wrapper names. * `Logger::log` and `Logger::flush` in `logforth-core` no longer panic when writing internal error reports to standard error fails. * `File` in `logforth-append-file` now opens segment files in append mode so external truncation does not leave NUL holes, avoids panicking on matching prefix and suffix edge cases or out-of-range timestamps, and avoids truncating rotation timestamps or file sizes on 32-bit targets. -* `PlainTextLayout` and `TextLayout` now return `Err` without modifying the output buffer instead of panicking when formatting fails, `TextLayout`, `LogfmtLayout`, `JsonLayout`, and `GoogleCloudLoggingLayout` return `Err` instead of panicking on out-of-range record timestamps, `JsonLayout` and `GoogleCloudLoggingLayout` serialize 128-bit integers outside 64-bit bounds as JSON numbers instead of degrading values or enclosing containers to strings, `LogfmtLayout` aligns key and value encoding with `go-logfmt` (escaping quoted strings with standard `\"`/`\\`/`\n`/`\r`/`\t`/`\u00XX` escapes instead of Rust `escape_debug()`, encoding `ValueView::None` as `null` and literal `"null"` as `"\"null\""`, stripping invalid characters from keys, and returning `Err` on empty keys), and `GoogleCloudLoggingLayout` gives explicit `Record` key-values precedence over colliding `Diagnostic` entries. +* `PlainTextLayout` and `TextLayout` now omit the separator space when the formatted message payload is empty and return `Err` without modifying the output buffer instead of panicking when formatting fails, `TextLayout`, `LogfmtLayout`, `JsonLayout`, and `GoogleCloudLoggingLayout` return `Err` instead of panicking on out-of-range record timestamps, `JsonLayout` and `GoogleCloudLoggingLayout` serialize 128-bit integers outside 64-bit bounds as JSON numbers instead of degrading values or enclosing containers to strings, `LogfmtLayout` aligns key and value encoding with `go-logfmt` (escaping quoted strings with standard `\"`/`\\`/`\n`/`\r`/`\t`/`\u00XX` escapes instead of Rust `escape_debug()`, encoding `ValueView::None` as `null` and literal `"null"` as `"\"null\""`, stripping invalid characters from keys, and returning `Err` on empty keys), and `GoogleCloudLoggingLayout` gives explicit `Record` key-values precedence over colliding `Diagnostic` entries. * `Async` in `logforth-append-async` now flushes inner appenders on `Drop` after draining queued records, isolates panics in inner appenders and `ErrorSink` during `append`, `flush`, and shutdown instead of terminating the worker thread or panicking in `Drop`, and waits for full bounded queues to drain during `flush` under `overflow_drop_incoming` instead of dropping the flush barrier. * `ThreadLocalDiagnostic` and `TaskLocalDiagnostic` now access thread-local storage via `LocalKey::try_with` so logging during thread-local teardown degrades to empty context instead of panicking. * `OpentelemetryLog` in `logforth-append-opentelemetry` now sets `LogRecord::set_timestamp` from `Record::time()` instead of overwriting the event timestamp with `SystemTime::now()`. diff --git a/core/src/layout/plain_text.rs b/core/src/layout/plain_text.rs index 10b06f0..b4009f6 100644 --- a/core/src/layout/plain_text.rs +++ b/core/src/layout/plain_text.rs @@ -103,8 +103,12 @@ impl PlainTextLayout { write!(writer, " {file}:{line}").map_err(make_error)?; } - let message = record.payload(); - write!(writer, " {message}").map_err(make_error)?; + let msg_start = writer.0.len(); + writer.0.push(b' '); + write!(writer, "{}", record.payload()).map_err(make_error)?; + if writer.0.len() == msg_start + 1 { + writer.0.pop(); + } record.key_values().visit(&mut writer)?; diags.visit(&mut writer) diff --git a/layouts/text/src/lib.rs b/layouts/text/src/lib.rs index e6acbb5..a47025d 100644 --- a/layouts/text/src/lib.rs +++ b/layouts/text/src/lib.rs @@ -331,8 +331,12 @@ impl TextLayout { write!(writer, " {file}:{line}").map_err(make_error)?; } - let message = record.payload(); - write!(writer, " {message}").map_err(make_error)?; + let msg_start = writer.0.len(); + writer.0.push(b' '); + write!(writer, "{}", record.payload()).map_err(make_error)?; + if writer.0.len() == msg_start + 1 { + writer.0.pop(); + } record.key_values().visit(&mut writer)?; diags.visit(&mut writer) diff --git a/tests-integration/tests/core_test/record_and_layout.rs b/tests-integration/tests/core_test/record_and_layout.rs index 41f643d..a1c3895 100644 --- a/tests-integration/tests/core_test/record_and_layout.rs +++ b/tests-integration/tests/core_test/record_and_layout.rs @@ -32,6 +32,7 @@ use logforth_core::record::Level; use logforth_core::record::LevelFilter; use logforth_core::record::Record; use logforth_core::record::RecordBuilder; +use tests_integration::RecordingAppender; use tests_integration::RecordingErrorSink; #[derive(Debug, PartialEq, Eq)] @@ -241,6 +242,33 @@ impl Diagnostic for FailingDiag { } } +#[test] +fn plain_text_layout_omits_separator_for_empty_payloads() { + let layout = PlainTextLayout::default(); + let base = RecordBuilder::new().time(SystemTime::UNIX_EPOCH).build(); + let kvs = [(Key::new("port"), Value::u64(8080))]; + let diags = StaticDiagnostic::new([("env", "prod")]); + let empty = ""; + let payload = format_args!("{empty}"); + for record in [base.to_builder().payload(payload).build(), base] { + let mut buf = Vec::new(); + layout.format(&record, &(), &mut buf).unwrap(); + assert_eq!(buf, b"0 INFO"); + + buf.clear(); + let record = record.to_builder().key_values(kvs.as_slice()).build(); + layout.format(&record, &diags, &mut buf).unwrap(); + assert_eq!(buf, b"0 INFO port=8080 env=prod"); + } + + let sink = RecordingAppender::with_layout(layout); + let logger = builder().dispatch(|d| d.append(sink.clone())).build(); + logforth_core::info!(logger, ["port" = 8080]); + let lines = sink.lines(); + assert!(lines[0].ends_with(" port=8080")); + assert!(!lines[0].ends_with(" port=8080")); +} + #[test] fn plain_text_layout_appends_to_existing_buffer_and_handles_pre_epoch_and_errors() { struct FailingDisplay; diff --git a/tests-integration/tests/layout_test/text.rs b/tests-integration/tests/layout_test/text.rs index 8ab3a5a..6c57c30 100644 --- a/tests-integration/tests/layout_test/text.rs +++ b/tests-integration/tests/layout_test/text.rs @@ -43,6 +43,44 @@ fn render(layout: &L, record: &Record<'_>, diags: &dyn Diagnostic) -> String::from_utf8(buf).unwrap() } +#[test] +fn text_layout_omits_separator_for_empty_payloads() { + let layout = TextLayout::new().utc().no_color(); + let no_ts = layout.clone().no_timestamp(); + let base = RecordBuilder::new().build(); + let kvs = [(Key::new("port"), Value::u64(8080))]; + let diags = StaticDiagnostic::new([("env", "prod")]); + let empty = ""; + let payload = format_args!("{empty}"); + for record in [base.to_builder().payload(payload).build(), base] { + assert_eq!(render(&no_ts, &record, &()), " INFO"); + let located = record + .to_builder() + .module_path_static("app::http") + .file_static("src/server/http.rs") + .line(Some(42)) + .build(); + assert_eq!( + render(&no_ts, &located, &()), + " INFO app::http: http.rs:42" + ); + let fields = located.to_builder().key_values(kvs.as_slice()).build(); + assert_eq!( + render(&no_ts, &fields, &diags), + " INFO app::http: http.rs:42 port=8080 env=prod" + ); + } + + let sink = RecordingAppender::with_layout(layout); + let logger = LoggerBuilder::new() + .dispatch(|d| d.append(sink.clone())) + .build(); + logforth::info!(logger, ["port" = 8080]); + let lines = sink.lines(); + assert!(lines[0].ends_with(" port=8080")); + assert!(!lines[0].ends_with(" port=8080")); +} + #[test] fn text_layout_formats_timestamps_precisions_structured_fields_and_toggles() { let ts = SystemTime::UNIX_EPOCH + Duration::new(1_700_000_000, 123_456_700);