From 0254d6c7171cd6a5677bf819f4d6481433ac9be4 Mon Sep 17 00:00:00 2001 From: tison Date: Tue, 1 Dec 2026 15:32:25 +0800 Subject: [PATCH 1/2] refactor!(json): rename JsonLayout kvs and diags fields to attributes and context Rename the serialized JSON sub-objects for structured record key-values and diagnostics in `JsonLayout` from `"kvs"` and `"diags"` to `"attributes"` and `"context"`. Using semantic field names (`"attributes"` for event properties, matching the OpenTelemetry Log Data Model, and `"context"` for ambient diagnostic metadata) avoids leaking internal data-structure and trait shorthand into external JSON log schemas. Signed-off-by: tison --- CHANGELOG.md | 1 + DESIGN.md | 2 +- README.md | 4 ++-- layouts/json/README.md | 4 ++-- layouts/json/src/lib.rs | 18 ++++++++++-------- tests-integration/tests/append_test/file.rs | 4 ++-- tests-integration/tests/layout_test/json.rs | 6 +++--- .../tests/logforth_test/pipeline.rs | 4 ++-- 8 files changed, 23 insertions(+), 20 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c8046a5..834db98 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -53,6 +53,7 @@ All significant changes to this project will be documented in this file. * `File` in `logforth-append-file` now writes directly to target segment files instead of writing to an unnumbered active file and shifting reverse-numbered archives on rollover. Unrotated output remains `[.]`, time-only rotation writes `.[.]`, and size rotation numbers segments in ascending order from `1` (oldest) as `[.].[.]`; `max_log_files` counts the active file toward the retention limit, and files created under the previous naming scheme are ignored or ordered by ascending sequence number until moved or removed. * `FileBuilder::rollover_size` in `logforth-append-file` now takes `NonZeroU64` instead of `NonZeroUsize` and rotates before a write would exceed the size limit rather than after; update callers passing `NonZeroUsize` to pass `NonZeroU64`. * `FileBuilder::build` in `logforth-append-file` now returns `Err` when `filename` or `filename_suffix` is empty, `.` or `..`, or contains path separators or NUL bytes. +* Rename `JsonLayout`'s structured record key-value and diagnostic sub-objects in `logforth-layout-json` from `"kvs"` and `"diags"` to `"attributes"` and `"context"`. * Align `GoogleCloudLoggingLayout` in `logforth-layout-google-cloud-logging` with Google Cloud Structured Logging: map all 24 `Level` severities to canonical `LogSeverity` strings (`DEBUG`, `INFO`, `NOTICE`, `WARNING`, `ERROR`, `CRITICAL`, `ALERT`, and `EMERGENCY`), format `logging.googleapis.com/labels` values as JSON strings, omit `logging.googleapis.com/sourceLocation` when `file`, `line`, and `module_path` are all unset, and extract Cloud Trace correlation fields only from `Diagnostic` `("trace_id", "span_id", "sampled")` entries (removing the `"trace_sampled"` diagnostic alias and keeping `Record::key_values()` entries as ordinary payload or label fields). * Replace `AsyncBuilder::buffered_lines_limit(Option)` with `AsyncBuilder::max_buffered_records(NonZeroUsize)` and change `AsyncBuilder::build` to return `Result` in `logforth-append-async`, returning `Err` instead of panicking when `thread_name` contains NUL bytes or OS thread creation fails; pass a `NonZeroUsize` limit when bounding buffered records (omit `max_buffered_records` for unbounded buffering) and handle the `Result` from `build`. * Remove the redundant `"timestamp"` event property (and `jiff` dependency) from `FastraceEvent` in `logforth-append-fastrace` and require an active sampled `SpanContext::current_local_parent()` before recording events (skipping parentless `LocalCollector::start()` scopes); read event timestamps from `fastrace::collector::EventRecord::timestamp_unix_ns` instead. diff --git a/DESIGN.md b/DESIGN.md index 3e1a384..2015c2e 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -72,4 +72,4 @@ Logforth separates three concerns into distinct primitives: ### Precedence and Flat-Format Envelope Fields - When `Record::key_values()` and `Diagnostic` emit the same key, map-based outputs give precedence to explicit `Record` key-values over `Diagnostic` entries. -- Nested layouts isolate structured entries under dedicated sub-objects (`kvs` and `diags`), whereas flat layouts and protocol sinks emit record metadata and key-values in a single flat namespace; avoid reusing envelope field names such as `timestamp`, `level`, `severity`, `message`, `module`, or `module_path` when targeting flat sinks. +- Nested layouts isolate structured entries under dedicated sub-objects (`attributes` and `context`), whereas flat layouts and protocol sinks emit record metadata and key-values in a single flat namespace; avoid reusing envelope field names such as `timestamp`, `level`, `severity`, `message`, `module`, or `module_path` when targeting flat sinks. diff --git a/README.md b/README.md index 8dff670..94609d7 100644 --- a/README.md +++ b/README.md @@ -100,8 +100,8 @@ fn main() -> Result<(), logforth::Error> { Only `payment gateway slow` appears on standard error, while `logs/checkout..jsonl` records both events: ```json -{"timestamp":"2024-08-11T22:44:57.172246+08:00","level":"INFO","module_path":"checkout","file":"src/main.rs","line":25,"message":"order accepted","kvs":{"order_id":42}} -{"timestamp":"2024-08-11T22:44:57.172310+08:00","level":"WARN","module_path":"checkout","file":"src/main.rs","line":26,"message":"payment gateway slow","kvs":{"order_id":42,"retry":1}} +{"timestamp":"2024-08-11T22:44:57.172246+08:00","level":"INFO","module_path":"checkout","file":"src/main.rs","line":25,"message":"order accepted","attributes":{"order_id":42}} +{"timestamp":"2024-08-11T22:44:57.172310+08:00","level":"WARN","module_path":"checkout","file":"src/main.rs","line":26,"message":"payment gateway slow","attributes":{"order_id":42,"retry":1}} ``` ### Working with the `log` crate diff --git a/layouts/json/README.md b/layouts/json/README.md index 9f9eeca..105d11d 100644 --- a/layouts/json/README.md +++ b/layouts/json/README.md @@ -24,10 +24,10 @@ logforth_core::info!(logger, ["port" = 8080], "server listening"); ## Output format and options -By default, `JsonLayout` serializes each record as a single-line JSON object containing an RFC 3339 `timestamp` with microsecond precision and timezone offset, `level`, `module_path`, `file`, and `line` (each omitted when unset), `message`, and optional `kvs` and `diags` objects (omitted when empty): +By default, `JsonLayout` serializes each record as a single-line JSON object containing an RFC 3339 `timestamp` with microsecond precision and timezone offset, `level`, `module_path`, `file`, and `line` (each omitted when unset), `message`, and optional `attributes` and `context` objects (omitted when empty): ```json -{"timestamp":"2024-08-11T22:44:57.172246+08:00","level":"INFO","module_path":"app::http","file":"src/server.rs","line":53,"message":"server listening","kvs":{"port":8080}} +{"timestamp":"2024-08-11T22:44:57.172246+08:00","level":"INFO","module_path":"app::http","file":"src/server.rs","line":53,"message":"server listening","attributes":{"port":8080}} ``` | Method | Effect | diff --git a/layouts/json/src/lib.rs b/layouts/json/src/lib.rs index b79aca2..42a1d08 100644 --- a/layouts/json/src/lib.rs +++ b/layouts/json/src/lib.rs @@ -23,8 +23,9 @@ //! - `file`: [`Record::file`] (omitted when unset); //! - `line`: [`Record::line`] (omitted when unset); //! - `message`: [`Record::payload`]; -//! - `kvs`: structured [`Record::key_values`] in callsite insertion order (omitted when empty); -//! - `diags`: structured [`Diagnostic`] entries (omitted when empty). +//! - `attributes`: structured [`Record::key_values`] in callsite insertion order (omitted when +//! empty); +//! - `context`: structured [`Diagnostic`] entries (omitted when empty). //! //! [`jiff`] is re-exported at the crate root so callers can configure [`TimeZone`] without adding a //! separate dependency. @@ -76,9 +77,10 @@ use serde::Serialize; /// /// # Envelope and Structured Fields /// -/// [`Record::key_values`] and [`Diagnostic`] entries are isolated under the `kvs` and `diags` -/// sub-objects (each omitted when empty) so user keys never collide with top-level envelope fields, -/// and are streamed directly into the output buffer without intermediate map allocations. +/// `attributes` contains [`Record::key_values`] in callsite insertion order, and `context` contains +/// [`Diagnostic`] entries. Each object is omitted when empty. These objects isolate user keys +/// from top-level envelope fields and are streamed directly into the output buffer without +/// intermediate map allocations. /// /// # Timestamps /// @@ -209,7 +211,7 @@ struct RecordLine<'a> { line: Option, message: std::fmt::Arguments<'a>, #[serde(skip_serializing_if = "KeyValues::is_empty")] - kvs: KeyValues<'a>, + attributes: KeyValues<'a>, } impl Layout for JsonLayout { @@ -233,7 +235,7 @@ impl Layout for JsonLayout { file: record.file(), line: record.line(), message: record.payload(), - kvs: record.key_values(), + attributes: record.key_values(), }; fn make_error(src: impl Into>) -> Error { @@ -252,7 +254,7 @@ impl Layout for JsonLayout { has_diag = true; let popped = buf.pop(); debug_assert_eq!(popped, Some(b'}')); - buf.extend_from_slice(b",\"diags\":{"); + buf.extend_from_slice(b",\"context\":{"); } else { buf.push(b','); } diff --git a/tests-integration/tests/append_test/file.rs b/tests-integration/tests/append_test/file.rs index cc32f9c..3f341ec 100644 --- a/tests-integration/tests/append_test/file.rs +++ b/tests-integration/tests/append_test/file.rs @@ -394,7 +394,7 @@ fn async_wrapped_file_flushes_concurrent_structured_records_on_drop() { for line in lines { assert!(line.starts_with('{') && line.ends_with('}')); assert!(line.contains("\"message\":\"processed batch\"")); - assert!(line.contains("\"diags\":{\"worker\":")); - assert!(line.contains("\"kvs\":{\"seq\":")); + assert!(line.contains("\"context\":{\"worker\":")); + assert!(line.contains("\"attributes\":{\"seq\":")); } } diff --git a/tests-integration/tests/layout_test/json.rs b/tests-integration/tests/layout_test/json.rs index 1869e76..a5b0ccf 100644 --- a/tests-integration/tests/layout_test/json.rs +++ b/tests-integration/tests/layout_test/json.rs @@ -112,7 +112,7 @@ fn json_layout_formats_timestamps_precisions_and_location_omission() { } #[test] -fn json_layout_streams_kvs_in_insertion_order_128bit_numbers_non_finite_floats_and_containers() { +fn json_layout_streams_attributes_in_insertion_order_with_structured_values() { let ts = SystemTime::UNIX_EPOCH + Duration::from_secs(1_700_000_000); let layout = JsonLayout::new().utc().precision(0); let diags = StaticDiagnostic::new([("env", "prod"), ("region", "us-east-1")]); @@ -153,11 +153,11 @@ fn json_layout_streams_kvs_in_insertion_order_128bit_numbers_non_finite_floats_a out, concat!( r#"{"timestamp":"2023-11-14T22:13:20Z","level":"WARN2","module_path":"app::worker","file":"src/worker.rs","line":99,"message":"handled \"req\" 42\nnext","#, - r#""kvs":{"zeta":1,"alpha":false,"none":null,"inf":null,"#, + r#""attributes":{"zeta":1,"alpha":false,"none":null,"inf":null,"#, r#""big_u":340282366920938463463374607431768211455,"big_i":-170141183460469231731687303715884105728,"#, r#""bytes":[104,105],"list":[340282366920938463463374607431768211455,null,"ok"],"#, r#""map":{"i128_min":-170141183460469231731687303715884105728}},"#, - r#""diags":{"env":"prod","region":"us-east-1"}}"#, + r#""context":{"env":"prod","region":"us-east-1"}}"#, ), ); } diff --git a/tests-integration/tests/logforth_test/pipeline.rs b/tests-integration/tests/logforth_test/pipeline.rs index fcdd173..282670b 100644 --- a/tests-integration/tests/logforth_test/pipeline.rs +++ b/tests-integration/tests/logforth_test/pipeline.rs @@ -285,8 +285,8 @@ fn multi_dispatch_pipeline_isolates_filters_diagnostics_and_sinks() { r#"{"region":"eu-central","amount":99}"#, ), ] { - let (record, diags) = line.split_once(r#","diags":{"#).unwrap(); - assert!(record.ends_with(&format!(r#""message":"{message}","kvs":{kvs}"#))); + let (record, diags) = line.split_once(r#","context":{"#).unwrap(); + assert!(record.ends_with(&format!(r#""message":"{message}","attributes":{kvs}"#))); assert!(diags.contains(r#""service":"payments""#)); assert!(diags.contains(r#""region":"us-east""#)); assert!(diags.contains(r#""trace_id":"00000000000000000000000000000042""#)); From b9c23440cd1151d46917a767893de5be5df634b8 Mon Sep 17 00:00:00 2001 From: tison Date: Tue, 1 Dec 2026 18:23:00 +0800 Subject: [PATCH 2/2] docs: drop undefined envelope jargon and buffer implementation details Replace undefined "envelope" terminology across `JsonLayout`, `GoogleCloudLoggingLayout`, `Journald`, `appenders/syslog/README.md`, and `DESIGN.md` with standard domain terms (`top-level fields`, `standard journal fields`, and `Syslog header`), remove internal buffer/allocation implementation details from `JsonLayout` rustdoc, and elide the explicit lifetime parameter on `valid_id` in `GoogleCloudLoggingLayout`. Signed-off-by: tison --- DESIGN.md | 4 ++-- appenders/journald/src/lib.rs | 2 +- appenders/syslog/README.md | 2 +- layouts/google-cloud-logging/src/lib.rs | 6 +++--- layouts/json/src/lib.rs | 12 +++++------- 5 files changed, 12 insertions(+), 14 deletions(-) diff --git a/DESIGN.md b/DESIGN.md index 2015c2e..5ff2a55 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -69,7 +69,7 @@ Logforth separates three concerns into distinct primitives: | `"span_id"` | `str` (hex) | `FastraceDiagnostic` | Extracted by `GoogleCloudLoggingLayout` (`logging.googleapis.com/spanId`) and `OpentelemetryLog` (`LogRecord::set_trace_context`) | | `"sampled"` | `bool` | `FastraceDiagnostic` | Extracted by `GoogleCloudLoggingLayout` (`logging.googleapis.com/trace_sampled`) and `OpentelemetryLog` (`TraceFlags`) | -### Precedence and Flat-Format Envelope Fields +### Precedence and Reserved Top-Level Fields - When `Record::key_values()` and `Diagnostic` emit the same key, map-based outputs give precedence to explicit `Record` key-values over `Diagnostic` entries. -- Nested layouts isolate structured entries under dedicated sub-objects (`attributes` and `context`), whereas flat layouts and protocol sinks emit record metadata and key-values in a single flat namespace; avoid reusing envelope field names such as `timestamp`, `level`, `severity`, `message`, `module`, or `module_path` when targeting flat sinks. +- Nested layouts isolate structured entries under dedicated sub-objects (`attributes` and `context`), whereas flat layouts and protocol sinks emit record metadata and key-values in a single flat namespace; avoid reusing reserved top-level field names such as `timestamp`, `level`, `severity`, `message`, `module`, or `module_path` when targeting flat sinks. diff --git a/appenders/journald/src/lib.rs b/appenders/journald/src/lib.rs index a285be8..d6cdbfb 100644 --- a/appenders/journald/src/lib.rs +++ b/appenders/journald/src/lib.rs @@ -240,7 +240,7 @@ impl Journald { /// Append a static custom journal field to every log entry, in registration order. /// /// `name` is sanitized using the key-mangling rules documented on [`Journald`]. Avoid reusing - /// standard envelope fields such as `MESSAGE` or `PRIORITY`; although journald permits multiple + /// standard journal fields such as `MESSAGE` or `PRIORITY`; although journald permits multiple /// values per field, tools such as `journalctl` typically display only the first `MESSAGE` or /// turn repeated keys into JSON arrays. /// diff --git a/appenders/syslog/README.md b/appenders/syslog/README.md index 3db149d..8a11bba 100644 --- a/appenders/syslog/README.md +++ b/appenders/syslog/README.md @@ -119,7 +119,7 @@ On Unix targets, `PosixSyslog` (`PosixSyslog::new()` or `PosixSyslog::builder()` ## Message format, payload layout, and severity mapping -- **Envelope ownership**: `SocketSyslog` formats the RFC 3164 or RFC 5424 header in Rust from `Record::time()` and `SyslogContext` (in `SyslogFormat::Rfc5424`, `MSGID` and `STRUCTURED-DATA` are emitted as `-`), whereas `PosixSyslog` passes only the priority and message body to `libc` `syslog(3)`, which prepends the local syslog header at call time. +- **Syslog header**: `SocketSyslog` formats the RFC 3164 or RFC 5424 header in Rust from `Record::time()` and `SyslogContext` (in `SyslogFormat::Rfc5424`, `MSGID` and `STRUCTURED-DATA` are emitted as `-`), whereas `PosixSyslog` passes only the priority and message body to `libc` `syslog(3)`, which prepends the local syslog header at call time. - **Payload-only default**: Without `SocketSyslogBuilder::layout` or `PosixSyslogBuilder::layout`, both `SocketSyslog` and `PosixSyslog` emit only `Record::payload()` as the message body (`MSG`); `Record::key_values()`, `Diagnostic` entries, and source location metadata (`module_path`, `file`, `line`) are omitted. - **Configuring a `Layout`**: Attach `.layout(...)` when structured fields or source locations should be rendered into `MSG`, such as `JsonLayout::new()`, `LogfmtLayout::new()`, or `TextLayout::new().no_timestamp().no_color()` (disabling `TextLayout`'s timestamp and ANSI color escapes avoids duplicating the syslog header timestamp or writing terminal escape sequences to syslog). diff --git a/layouts/google-cloud-logging/src/lib.rs b/layouts/google-cloud-logging/src/lib.rs index b225b93..3fce274 100644 --- a/layouts/google-cloud-logging/src/lib.rs +++ b/layouts/google-cloud-logging/src/lib.rs @@ -106,8 +106,8 @@ const KEY_SAMPLED: &str = "sampled"; /// top-level `jsonPayload` by default, or routed to `logging.googleapis.com/labels` as JSON strings /// when their keys are registered via [`GoogleCloudLoggingLayout::label_keys`]. Explicit /// [`Record::key_values`] override colliding [`Diagnostic`] entries. Avoid reusing special -/// top-level envelope keys (`severity`, `timestamp`, `message`, or `logging.googleapis.com/*`) for -/// custom payload fields. +/// top-level keys (`severity`, `timestamp`, `message`, or `logging.googleapis.com/*`) for custom +/// payload fields. /// /// # Errors /// @@ -212,7 +212,7 @@ fn value_to_cow_str(value: ValueView<'_>) -> Cow<'static, str> { } } -fn valid_id<'a>(value: ValueView<'a>, digits: usize) -> Option<&'a str> { +fn valid_id(value: ValueView<'_>, digits: usize) -> Option<&str> { value.to_str().filter(|s| { s.len() == digits && s.bytes().all(|b| b.is_ascii_hexdigit()) diff --git a/layouts/json/src/lib.rs b/layouts/json/src/lib.rs index 42a1d08..9fe8dc0 100644 --- a/layouts/json/src/lib.rs +++ b/layouts/json/src/lib.rs @@ -14,8 +14,7 @@ //! Single-line JSON layout for formatting structured log records. //! -//! [`JsonLayout`] implements [`Layout`] by serializing each [`Record`] directly into the caller's -//! byte buffer as a single-line JSON object containing: +//! [`JsonLayout`] formats each [`Record`] as a single-line JSON object containing: //! - `timestamp`: an RFC 3339 timestamp with configurable fractional-second //! [`JsonLayout::precision`] and timezone offset or UTC `Z` suffix; //! - `level`: the severity name (`TRACE`..=`FATAL4`); @@ -75,12 +74,11 @@ use serde::Serialize; /// {"timestamp":"2024-08-11T22:44:57.172353+08:00","level":"TRACE","module_path":"file","file":"examples/file.rs","line":55,"message":"Hello trace!"} /// ``` /// -/// # Envelope and Structured Fields +/// # Structured Fields /// -/// `attributes` contains [`Record::key_values`] in callsite insertion order, and `context` contains -/// [`Diagnostic`] entries. Each object is omitted when empty. These objects isolate user keys -/// from top-level envelope fields and are streamed directly into the output buffer without -/// intermediate map allocations. +/// [`Record::key_values`] are serialized under `attributes` in callsite insertion order, and +/// [`Diagnostic`] entries are serialized under `context`. Each object is omitted when empty, +/// keeping user keys separate from top-level fields. /// /// # Timestamps ///