Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,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.
* `TextLayout`, `LogfmtLayout`, `JsonLayout`, and `GoogleCloudLoggingLayout` now 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 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()`.
Expand Down
69 changes: 53 additions & 16 deletions core/src/layout/plain_text.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,16 @@
// See the License for the specific language governing permissions and
// limitations under the License.

use std::io::Write;
use std::fmt;
use std::fmt::Write;
use std::time::SystemTime;

use crate::Diagnostic;
use crate::Error;
use crate::Layout;
use crate::kv::KeyView;
use crate::kv::ValueView;
use crate::kv::Visitor;
use crate::record::Record;

/// A zero-dependency layout that formats log records as single-line plain text.
Expand All @@ -36,6 +38,11 @@ use crate::record::Record;
/// 1760092868730581000 TRACE simple: simple.rs:28 Hello trace!
/// ```
///
/// # Errors
///
/// [`Layout::format`] returns an [`Error`] without modifying `buf` if formatting the record or
/// visiting key-values or diagnostics fails.
///
/// # Examples
///
/// ```
Expand All @@ -52,40 +59,70 @@ impl PlainTextLayout {
pub const fn new() -> Self {
Self {}
}
}

impl Layout for PlainTextLayout {
fn format(
fn do_format(
&self,
record: &Record,
diags: &dyn Diagnostic,
buf: &mut Vec<u8>,
) -> Result<(), Error> {
fn make_error(err: fmt::Error) -> Error {
Error::new("failed to format log record").with_source(err)
}

struct FmtBuf<'a>(&'a mut Vec<u8>);

impl Write for FmtBuf<'_> {
fn write_str(&mut self, s: &str) -> fmt::Result {
self.0.extend_from_slice(s.as_bytes());
Ok(())
}
}

impl Visitor for FmtBuf<'_> {
fn visit(&mut self, key: KeyView, value: ValueView) -> Result<(), Error> {
write!(self, " {key}={value}").map_err(make_error)
}
}

let mut writer = FmtBuf(buf);
match record.time().duration_since(SystemTime::UNIX_EPOCH) {
Ok(dur) => write!(buf, "{}", dur.as_nanos()).unwrap(),
Err(err) => write!(buf, "-{}", err.duration().as_nanos()).unwrap(),
Ok(dur) => write!(writer, "{}", dur.as_nanos()).map_err(make_error)?,
Err(err) => write!(writer, "-{}", err.duration().as_nanos()).map_err(make_error)?,
}

let level = record.level().name();
write!(buf, " {level:>6}").unwrap();
write!(writer, " {level:>6}").map_err(make_error)?;

if let Some(module_path) = record.module_path() {
write!(buf, " {module_path}:").unwrap();
write!(writer, " {module_path}:").map_err(make_error)?;
}

if let Some(file) = record.filename() {
let line = record.line().unwrap_or_default();
write!(buf, " {file}:{line}").unwrap();
write!(writer, " {file}:{line}").map_err(make_error)?;
}

let message = record.payload();
write!(buf, " {message}").unwrap();
write!(writer, " {message}").map_err(make_error)?;

let mut visit = |key: KeyView, value: ValueView| {
write!(buf, " {key}={value}").unwrap();
Ok(())
};
record.key_values().visit(&mut visit)?;
diags.visit(&mut visit)
record.key_values().visit(&mut writer)?;
diags.visit(&mut writer)
}
}

impl Layout for PlainTextLayout {
fn format(
&self,
record: &Record,
diags: &dyn Diagnostic,
buf: &mut Vec<u8>,
) -> Result<(), Error> {
let start_len = buf.len();
if let Err(err) = self.do_format(record, diags, buf) {
buf.truncate(start_len);
return Err(err);
}
Ok(())
}
}
68 changes: 53 additions & 15 deletions layouts/text/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,8 @@
pub extern crate anstyle;
pub extern crate jiff;

use std::io::Write;
use std::fmt;
use std::fmt::Write;

use anstyle::AnsiColor;
use anstyle::Color;
Expand All @@ -60,6 +61,7 @@ use logforth_core::Diagnostic;
use logforth_core::Error;
use logforth_core::kv::KeyView;
use logforth_core::kv::ValueView;
use logforth_core::kv::Visitor;
use logforth_core::layout::Layout;
use logforth_core::record::Level;
use logforth_core::record::Record;
Expand Down Expand Up @@ -95,6 +97,12 @@ use logforth_core::record::Record;
/// [`TextLayout::precision`] (default: `6` for microseconds), [`TextLayout::timezone`] (default:
/// [`TimeZone::system`]), and [`TextLayout::utc`].
///
/// # Errors
///
/// [`Layout::format`] returns an [`Error`] without modifying `buf` if timestamps are enabled and
/// [`Record::time`] is outside the range of [`Timestamp`], if formatting fails, or if visiting
/// key-values or diagnostics fails.
///
/// # Examples
///
/// ```
Expand Down Expand Up @@ -263,10 +271,8 @@ impl TextLayout {
self.timezone = None;
self
}
}

impl Layout for TextLayout {
fn format(
fn do_format(
&self,
record: &Record,
diags: &dyn Diagnostic,
Expand All @@ -280,40 +286,72 @@ impl Layout for TextLayout {
Some(tz) => printer.print_timestamp_with_offset(&ts, tz.to_offset(ts), &mut *buf),
None => printer.print_timestamp(&ts, &mut *buf),
}
.unwrap();
.map_err(|err| Error::new("failed to format record timestamp").with_source(err))?;
buf.push(b' ');
}

fn make_error(err: fmt::Error) -> Error {
Error::new("failed to format log record").with_source(err)
}

struct FmtBuf<'a>(&'a mut Vec<u8>);

impl Write for FmtBuf<'_> {
fn write_str(&mut self, s: &str) -> fmt::Result {
self.0.extend_from_slice(s.as_bytes());
Ok(())
}
}

impl Visitor for FmtBuf<'_> {
fn visit(&mut self, key: KeyView, value: ValueView) -> Result<(), Error> {
write!(self, " {key}={value}").map_err(make_error)
}
}

let mut writer = FmtBuf(buf);
let level = record.level().name();
let style = if self.no_color {
Style::new()
} else {
self.colors.color_for(record.level()).on_default()
};
write!(buf, "{style}{level:>6}{style:#}").unwrap();
write!(writer, "{style}{level:>6}{style:#}").map_err(make_error)?;

if !self.no_module_path
&& let Some(module_path) = record.module_path()
{
write!(buf, " {module_path}:").unwrap();
write!(writer, " {module_path}:").map_err(make_error)?;
}

if !self.no_file
&& let Some(file) = record.filename()
{
let line = record.line().unwrap_or_default();
write!(buf, " {file}:{line}").unwrap();
write!(writer, " {file}:{line}").map_err(make_error)?;
}

let message = record.payload();
write!(buf, " {message}").unwrap();
write!(writer, " {message}").map_err(make_error)?;

let mut visit = |key: KeyView, value: ValueView| {
write!(buf, " {key}={value}").unwrap();
Ok(())
};
record.key_values().visit(&mut visit)?;
diags.visit(&mut visit)
record.key_values().visit(&mut writer)?;
diags.visit(&mut writer)
}
}

impl Layout for TextLayout {
fn format(
&self,
record: &Record,
diags: &dyn Diagnostic,
buf: &mut Vec<u8>,
) -> Result<(), Error> {
let start_len = buf.len();
if let Err(err) = self.do_format(record, diags, buf) {
buf.truncate(start_len);
return Err(err);
}
Ok(())
}
}

Expand Down
39 changes: 38 additions & 1 deletion tests-integration/tests/core_test/record_and_layout.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@
// See the License for the specific language governing permissions and
// limitations under the License.

use std::error::Error as _;
use std::fmt;
use std::time::Duration;
use std::time::SystemTime;

Expand Down Expand Up @@ -241,6 +243,14 @@ impl Diagnostic for FailingDiag {

#[test]
fn plain_text_layout_appends_to_existing_buffer_and_handles_pre_epoch_and_errors() {
struct FailingDisplay;

impl fmt::Display for FailingDisplay {
fn fmt(&self, _: &mut fmt::Formatter<'_>) -> fmt::Result {
Err(fmt::Error)
}
}

let ts = SystemTime::UNIX_EPOCH + Duration::new(1_700_000_000, 123_456_700);
let kvs = [
(Key::new("port"), Value::u64(8080)),
Expand Down Expand Up @@ -294,10 +304,37 @@ fn plain_text_layout_appends_to_existing_buffer_and_handles_pre_epoch_and_errors
);

// Diagnostic visit errors propagate out of `PlainTextLayout::format`.
let mut buf = b"prefix|".to_vec();
let err = layout
.format(&pre_epoch, &FailingDiag, &mut Vec::new())
.format(&pre_epoch, &FailingDiag, &mut buf)
.unwrap_err();
assert_eq!(err.message(), "diagnostic unavailable");
assert_eq!(buf, b"prefix|");

let errors = RecordingErrorSink::default();
let logger = builder()
.error_sink(errors.clone())
.dispatch(|d| d.append(Testing::new().with_layout(PlainTextLayout::new())))
.build();

let kvs = [(Key::new("field"), Value::display(&FailingDisplay))];
let payload = format_args!("{FailingDisplay}");
for record in [
RecordBuilder::new().payload(payload).build(),
RecordBuilder::new().key_values(kvs.as_slice()).build(),
] {
let err = layout.format(&record, &(), &mut buf).unwrap_err();
assert_eq!(err.message(), "failed to format log record");
assert!(err.source().is_some());
assert_eq!(buf, b"prefix|");
logger.log(&record);
}
logger.flush();
let recorded = errors.errors();
assert_eq!(recorded.len(), 2);
for report in recorded {
assert!(report.starts_with("failed to append record: failed to format log record"));
}
}

#[derive(Debug)]
Expand Down
33 changes: 30 additions & 3 deletions tests-integration/tests/layout_test/text.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@
// See the License for the specific language governing permissions and
// limitations under the License.

use std::error::Error as _;
use std::fmt;
use std::time::Duration;
use std::time::SystemTime;

Expand Down Expand Up @@ -255,6 +257,14 @@ impl Diagnostic for FailingDiag {

#[test]
fn text_layout_surfaces_out_of_range_timestamp_and_diagnostic_errors_without_panicking() {
struct FailingDisplay;

impl fmt::Display for FailingDisplay {
fn fmt(&self, _: &mut fmt::Formatter<'_>) -> fmt::Result {
Err(fmt::Error)
}
}

let out_of_range = SystemTime::UNIX_EPOCH + Duration::from_secs(300_000_000_000);
let bad_ts_record = RecordBuilder::new()
.time(out_of_range)
Expand Down Expand Up @@ -282,26 +292,43 @@ fn text_layout_surfaces_out_of_range_timestamp_and_diagnostic_errors_without_pan
.payload(format_args!("ok"))
.build();
let diag_err = layout
.format(&valid_record, &FailingDiag, &mut Vec::new())
.format(&valid_record, &FailingDiag, &mut buf)
.unwrap_err();
assert_eq!(diag_err.message(), "diagnostic failure");
assert_eq!(buf, b"untouched");

// End-to-end pipeline routes timestamp formatting failures into `ErrorSink`.
let errors = RecordingErrorSink::default();
let sink = RecordingAppender::with_layout(layout);
let sink = RecordingAppender::with_layout(layout.clone());
let logger = LoggerBuilder::new()
.error_sink(errors.clone())
.dispatch(|d| d.append(sink.clone()))
.build();

logger.log(&bad_ts_record);

let kvs = [(Key::new("field"), Value::display(&FailingDisplay))];
let payload = format_args!("{FailingDisplay}");
for record in [
RecordBuilder::new().payload(payload).build(),
RecordBuilder::new().key_values(kvs.as_slice()).build(),
] {
let err = layout.format(&record, &(), &mut buf).unwrap_err();
assert_eq!(err.message(), "failed to format log record");
assert!(err.source().is_some());
assert_eq!(buf, b"untouched");
logger.log(&record);
}
logger.flush();
assert!(sink.lines().is_empty());
let recorded = errors.errors();
assert_eq!(recorded.len(), 1);
assert_eq!(recorded.len(), 3);
assert!(
recorded[0].starts_with("failed to append record: invalid record timestamp"),
"unexpected error report: {}",
recorded[0]
);
for report in &recorded[1..] {
assert!(report.starts_with("failed to append record: failed to format log record"));
}
}
Loading