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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 `<filename>[.<suffix>]`, time-only rotation writes `<filename>.<period>[.<suffix>]`, and size rotation numbers segments in ascending order from `1` (oldest) as `<filename>[.<period>].<seq>[.<suffix>]`; `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<usize>)` with `AsyncBuilder::max_buffered_records(NonZeroUsize)` and change `AsyncBuilder::build` to return `Result<Async, Error>` 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.
Expand Down
4 changes: 2 additions & 2 deletions DESIGN.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 (`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 reserved top-level field names such as `timestamp`, `level`, `severity`, `message`, `module`, or `module_path` when targeting flat sinks.
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -100,8 +100,8 @@ fn main() -> Result<(), logforth::Error> {
Only `payment gateway slow` appears on standard error, while `logs/checkout.<date>.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
Expand Down
2 changes: 1 addition & 1 deletion appenders/journald/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
///
Expand Down
2 changes: 1 addition & 1 deletion appenders/syslog/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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).

Expand Down
6 changes: 3 additions & 3 deletions layouts/google-cloud-logging/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
///
Expand Down Expand Up @@ -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())
Expand Down
4 changes: 2 additions & 2 deletions layouts/json/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand Down
22 changes: 11 additions & 11 deletions layouts/json/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,17 +14,17 @@

//! 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`);
//! - `module_path`: [`Record::module_path`] (omitted when unset);
//! - `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.
Expand Down Expand Up @@ -74,11 +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
///
/// [`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.
/// [`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
///
Expand Down Expand Up @@ -209,7 +209,7 @@ struct RecordLine<'a> {
line: Option<u32>,
message: std::fmt::Arguments<'a>,
#[serde(skip_serializing_if = "KeyValues::is_empty")]
kvs: KeyValues<'a>,
attributes: KeyValues<'a>,
}

impl Layout for JsonLayout {
Expand All @@ -233,7 +233,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<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Error {
Expand All @@ -252,7 +252,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',');
}
Expand Down
4 changes: 2 additions & 2 deletions tests-integration/tests/append_test/file.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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\":"));
}
}
6 changes: 3 additions & 3 deletions tests-integration/tests/layout_test/json.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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")]);
Expand Down Expand Up @@ -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"}}"#,
),
);
}
Expand Down
4 changes: 2 additions & 2 deletions tests-integration/tests/logforth_test/pipeline.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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""#));
Expand Down
Loading