Skip to content
Closed
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
5 changes: 3 additions & 2 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,11 +39,11 @@ All significant changes to this project will be documented in this file.
* Replace `&[Box<dyn Diagnostic>]` with `&dyn Diagnostic` across `Filter::filter`, `Layout::format`, `Append::append`, and `MakeBody::create` in `logforth-core`, `logforth`, and peripheral crates, and relax the `'static` supertrait bound on `Diagnostic` to the `Box<dyn Diagnostic>` registration boundary; traverse diagnostics via `diags.visit(&mut visitor)` instead of iterating a slice, and pass `&()` for an empty diagnostic context.
* Change `Layout::format` in `logforth-core` and built-in layouts to append formatted bytes into a caller-supplied `&mut Vec<u8>` and return `Result<(), Error>` instead of `Result<Vec<u8>, Error>`.
* Replace `Filter::{enabled, matches}` and `FilterCriteria` in `logforth-core` with `Filter::{filter_level(&self, level: Level) -> FilterResult, filter(&self, record: &Record, diags: &dyn Diagnostic) -> FilterResult}`, precomputing level bitmasks across `Level::ALL` at `Logger` build time and changing `Logger::enabled` to accept `Level` instead of `&FilterCriteria`.
* Remove `Record::target`, `RecordBuilder::{target, target_static}`, and `RecordOwned::target` from `logforth-core`, updating `PlainTextLayout`, `TextLayout`, `JsonLayout` (now serializing `"module_path"`), and `LogfmtLayout` to read `Record::module_path`, stopping `OpentelemetryLog` from calling `LogRecord::set_target` (preserving the configured `InstrumentationScope` name), and omitting the non-standard `TARGET` field in `Journald`.
* Remove `Record::target`, `RecordBuilder::{target, target_static}`, and `RecordOwned::target` from `logforth-core` in favor of explicit `Record::logger_name`: `PlainTextLayout`, `TextLayout`, `JsonLayout` (now serializing `"module_path"`), and `LogfmtLayout` read `Record::module_path` by default instead of repeating the module path as a target, `OpentelemetryLog` calls `LogRecord::set_target` only when `Record::logger_name` is set (preserving the configured `InstrumentationScope` name on unnamed loggers), and `Journald` omits the non-standard `TARGET` field.
* Change `Record::filename` from `Cow<'a, str>` to `Option<&'a str>`, change `Record::key_values` from `&KeyValues<'a>` to `KeyValues<'a>` by value, and replace `Record::builder` with `RecordBuilder::new` in `logforth-core`; unwrap or match `Record::filename` when a fallback empty string is needed.
* `RustLogFilterBuilder::{from_default_env, from_default_env_or, from_env, from_env_or, from_spec}` in `logforth-filter-rustlog` now return `Result<Self, Error>` and fail fast on malformed directives or non-UTF-8 environment variables instead of printing warnings to standard error, `RustLogFilterBuilder::{filter_level, filter_module}` are renamed to `{fallback, prefix}`, `RustLogFilterBuilder::try_from_spec` is removed, and `From<&str>` for `RustLogFilter` is replaced with `TryFrom<&str>`.
* Promote `Logger`, `LoggerBuilder`, `DispatchBuilder`, and `builder` to the `logforth` crate root (removing `logforth::core`), remove `starter_log::builder` and `LogStarterBuilder`, unify `LogStarterTestingBuilder` and `LogStarterStdStreamBuilder` into `starter_log::LogStarter`, and replace `apply` / `try_apply` with `starter_log::LogStarterExt::{install, try_install}` (implemented for `Logger`, `LoggerBuilder`, `LogStarter`, and `LogBridge`).
* Reserve the `logforth.` key prefix in key-value pairs for Logforth (`"logforth.log_target"` carries explicit `log` target overrides from `LogBridge` into `RustLogFilter`; see [DESIGN.md](DESIGN.md#appendix-key-value-naming-conventions)).
* Reserve the `logforth.` key prefix in key-value pairs for Logforth (see [DESIGN.md](DESIGN.md#appendix-key-value-naming-conventions)).
* `LogBridge::new` in `logforth-bridge-log` now accepts `Logger` by value instead of `impl Into<Arc<Logger>>` (pass `logger.clone()` when retaining another handle), and `Deref<Target = Logger>` is replaced with explicit `LogBridge::{logger, into_logger}` accessors so `Log::{enabled, log}` no longer collide with `Logger::{enabled, log}`.
* Remove the `const APPEND: bool` generic parameter from `DispatchBuilder` in `logforth-core`; `DispatchBuilder::append` now returns `Self` in any order, and dispatches configured with no appenders are skipped when registered on `LoggerBuilder`.
* Remove `Copy` from `ThreadLocalDiagnostic` in `logforth-core`, `TaskLocalDiagnostic` in `logforth-diagnostic-task-local`, and `FastraceDiagnostic` in `logforth-diagnostic-fastrace`.
Expand All @@ -65,6 +65,7 @@ All significant changes to this project will be documented in this file.
* Add native structured logging macros (`log!`, `trace!`, `debug!`, `info!`, `warn!`, `error!`, and `fatal!`) in `logforth-core` and `logforth` supporting bracketed `"key" = value` fields on explicit `Logger` handles.
* Add `Error::message` and `RecordBuilder::time` in `logforth-core` to borrow an error's own message string and construct records with an explicit observed timestamp.
* Make `Logger` a pointer-sized `Clone` and `Default` handle over a shared pipeline, add `const fn Logger::noop()`, `LoggerBuilder::new()` and `RecordBuilder::new()` (with `Default`), `const fn new()` on `PlainTextLayout`, `ThreadLocalDiagnostic`, `StderrErrorSink`, and `BlackHoleErrorSink`, and `new()` on `Stdout`, `Stderr`, and `Testing` in `logforth-core`, add `const fn new()` on `TaskLocalDiagnostic` in `logforth-diagnostic-task-local`, `FastraceDiagnostic` in `logforth-diagnostic-fastrace`, `FastraceEvent` in `logforth-append-fastrace`, and `GoogleCloudLoggingLayout` in `logforth-layout-google-cloud-logging`, add `new()` on `TextLayout`, `LogfmtLayout`, and `JsonLayout`, and implement `Clone`, `Default`, and `From<Logger>` for `LogBridge` in `logforth-bridge-log`.
* Add hierarchical `Logger::{name, named}`, narrowing `Logger::with_level_filter`, `Record::{logger_name, logger_name_static}`, and `RecordBuilder::{logger_name, logger_name_static}` in `logforth-core` (re-exported in `logforth`), routing explicit logger names and `LogBridge` custom `log` targets through `RustLogFilter` (falling back to `Record::module_path`), built-in layouts (`[logger]` in `PlainTextLayout` and `TextLayout`, `"logger"` in `JsonLayout` and `GoogleCloudLoggingLayout`, and `logger=` in `LogfmtLayout`), and `OpentelemetryLog` (`LogRecord::set_target`).
* Add `Level::ALL` in `logforth-core` and `ValueOwned::{from_serde, try_from_serde}` (behind the `serde` feature) to convert `serde::Serialize` values into structured `ValueOwned` trees without panicking.
* Add `LogBridge::{max_level, logger, into_logger, try_install, install}` in `logforth-bridge-log`, and add `starter_log::{LogStarterExt, LogStarter::try_build}` (with `Debug` for `LogStarter`), `layout::{json, logfmt}` module re-exports, and the `serde` feature (`logforth-core/serde`) in `logforth`, updating `log::set_max_level` automatically from enabled logger levels on installation.
* Add `LoggerBuilder::error_sink` and `starter_log::LogStarter::error_sink` to configure runtime error handling.
Expand Down
16 changes: 6 additions & 10 deletions DESIGN.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,11 @@ This document states the workspace-wide architectural direction, pipeline invari

Logforth separates three concerns into distinct primitives:

| Dimension | Question Answered | Representation in Logforth |
| :------------------- | :-------------------------------------------------------- | :------------------------------------------------------- |
| Source location | Where in the source tree was the event emitted? | Compile-time `module_path`, `file`, `line`, and `column` |
| Channel (`Logger`) | Which reliability, schema, and lifecycle stream owns it? | Explicit `Logger` instances |
| Fan-out (`Dispatch`) | Which output slices and destinations receive this stream? | Ordered `Dispatch` branches inside a `Logger` |
| Dimension | Question Answered | Representation in Logforth |
| :------------------- | :-------------------------------------------------------- | :----------------------------------------------------------------------------------- |
| Source location | Where in the source tree was the event emitted? | Compile-time `module_path`, `file`, `line`, and `column` |
| Channel (`Logger`) | Which reliability, schema, and lifecycle stream owns it? | Explicit `Logger` handles (with optional `named` scopes and `with_level_filter`) |
| Fan-out (`Dispatch`) | Which output slices and destinations receive this stream? | Ordered `Dispatch` branches inside a `Logger` |

- `Logger` is a lightweight `Clone` handle over a shared immutable pipeline, with no ambient global singleton in `logforth-core`. Applications expose process-wide channels through explicit statics or dependency injection, while libraries accepting an optional logger default to a zero-allocation `Logger::noop()`.
- All five extension points (`Filter`, `Diagnostic`, `Layout`, `Append`, and `ErrorSink`) are open object-safe traits paired with concrete types rather than closed enums or ad-hoc callbacks, forwarding shared references (`Arc<T>` and `&'static T`) so dispatches and loggers compose as a directed acyclic graph. `Diagnostic` omits a `'static` supertrait bound so decorators can chain stack-borrowed per-call context without allocation, enforcing `'static` only when registering long-lived diagnostics on a `Dispatch`.
Expand Down Expand Up @@ -55,10 +55,6 @@ Logforth separates three concerns into distinct primitives:

- Keys prefixed with `logforth.` are reserved by Logforth. Adding new `logforth.*` keys in minor releases is SemVer-compatible; application code must not emit `logforth.*` keys for domain fields unless intentionally invoking a documented behavior.

| Key | Value Type | Producers | Consumers and Semantics |
| :---------------------- | :--------- | :----------------------------------------- | :---------------------------------------------------------------------- |
| `"logforth.log_target"` | `str` | `LogBridge` (when `target != module_path`) | Matched by `RustLogFilter` before falling back to `Record::module_path` |

### Well-Known Shared Keys

- Unprefixed well-known keys preserve standard field names in external log outputs while coordinating typed context between diagnostics, layouts, and appenders:
Expand All @@ -72,4 +68,4 @@ Logforth separates three concerns into distinct primitives:
### 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 reserved top-level 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`, `logger`, `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 @@ -20,7 +20,7 @@ Logforth is a structured logging framework for Rust built around composable logg

A logger pipeline consists of one or more dispatches, each of which filters, enriches, and routes log records to one or more appenders. The same call site can send terse alerts to the terminal, detailed JSON lines to rotated files, and structured events to telemetry backends like OpenTelemetry without duplicating logging code.

Loggers are ordinary values rather than a mandatory global singleton. Applications and libraries can pass separate `Logger` instances to subsystems or tests, or install one globally to collect [`log`] records from the wider Rust ecosystem.
Loggers are ordinary values rather than a mandatory global singleton. Applications and libraries can pass separate `Logger` instances to subsystems or tests, derive hierarchical named or level-scoped handles with `Logger::named` and `Logger::with_level_filter`, or install one globally to collect [`log`] records from the wider Rust ecosystem.

## Getting started

Expand Down Expand Up @@ -163,7 +163,7 @@ Runnable end-to-end scenarios live in the [`examples`](examples) workspace crate
| | [`JsonLayout`] | `layout-json` | Single-line JSON output. |
| | [`GoogleCloudLoggingLayout`] | `layout-google-cloud-logging` | Structured JSON output for Google Cloud Logging. |
| Filters | [`LevelFilter`] | *built-in* | Filter records by severity threshold. |
| | [`RustLogFilter`] | `filter-rustlog` | Filter by module or target prefix using `RUST_LOG` directives. |
| | [`RustLogFilter`] | `filter-rustlog` | Filter by logger name or module prefix using `RUST_LOG` directives. |
| Diagnostics | [`StaticDiagnostic`] | *built-in* | Attach process-wide key-value fields such as service name or version. |
| | [`ThreadLocalDiagnostic`] | *built-in* | Attach scoped key-value fields on the current thread. |
| | [`TaskLocalDiagnostic`] | `diagnostic-task-local` | Attach scoped key-value fields to an async `Future`. |
Expand Down
2 changes: 1 addition & 1 deletion appenders/journald/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ Logforth's 24 `Level` variants map to syslog/journal priority numbers following

1. Empty keys become `EMPTY`.
2. ASCII lowercase letters are uppercased, and characters outside `A`..=`Z`, `0`..=`9`, and `_` are replaced with `_`.
3. Keys starting with `_` or `0`..=`9` after sanitization are prefixed with `ESCAPED_` (for example, `_pid` becomes `ESCAPED__PID` and `logforth.log_target` becomes `LOGFORTH_LOG_TARGET`).
3. Keys starting with `_` or `0`..=`9` after sanitization are prefixed with `ESCAPED_` (for example, `_pid` becomes `ESCAPED__PID` and `http.method` becomes `HTTP_METHOD`).
4. Names exceeding 64 bytes are truncated to 64 bytes.

## Operational notes
Expand Down
15 changes: 8 additions & 7 deletions appenders/opentelemetry/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -54,16 +54,17 @@ Each `Record` is projected onto an `opentelemetry_sdk::logs::SdkLogRecord`:
| `observed_timestamp` | `SystemTime::now()` captured when `OpentelemetryLog::append` processes the record. |
| `severity_number` / `text` | 1-to-1 mapping across all 24 `Level` variants (`Trace`..=`Fatal4` -> `Severity::Trace`..=`Severity::Fatal4`) and `Level::name()`. |
| `body` | `AnyValue::String` from `Record::payload()`, or custom `AnyValue` produced by `MakeBody` (such as `MakeBodyLayout`). |
| `target` | `Record::logger_name()` when present (exported as the OTLP `ScopeLogs` scope name); unnamed records retain `new(name, ...)`. |
| `trace_context` | Extracted from `Diagnostic` `("trace_id", "span_id")` (32- and 16-digit non-zero hex) and optional boolean `"sampled"`. |
| `attributes` | Present `module_path`, `file`, `line`, `column`, followed by typed `Record::key_values()` and unshadowed `Diagnostic` entries. |

| `OpentelemetryLogBuilder` method | Effect |
| :------------------------------- | :-------------------------------------------------------------------------------------------------------------------------- |
| `new(name, log_exporter)` | Configures the `InstrumentationScope` name and registers `log_exporter` (`impl LogExporter + 'static`) in a batch pipeline. |
| `label(key, value)` | Adds a resource attribute (`opentelemetry::KeyValue`) merged onto `opentelemetry_sdk::Resource::builder()`. |
| `labels(iter)` | Adds multiple `(key, value)` resource attributes. |
| `make_body(make_body)` | Overrides how `SdkLogRecord` bodies are constructed (for example, `MakeBodyLayout::new(JsonLayout::new())`). |
| `build()` | Builds the `OpentelemetryLog` appender. |
| `OpentelemetryLogBuilder` method | Effect |
| :------------------------------- | :---------------------------------------------------------------------------------------------------------------------------------- |
| `new(name, log_exporter)` | Configures the default `InstrumentationScope` name and registers `log_exporter` (`impl LogExporter + 'static`) in a batch pipeline. |
| `label(key, value)` | Adds a resource attribute (`opentelemetry::KeyValue`) merged onto `opentelemetry_sdk::Resource::builder()`. |
| `labels(iter)` | Adds multiple `(key, value)` resource attributes. |
| `make_body(make_body)` | Overrides how `SdkLogRecord` bodies are constructed (for example, `MakeBodyLayout::new(JsonLayout::new())`). |
| `build()` | Builds the `OpentelemetryLog` appender. |

`opentelemetry` and `opentelemetry_sdk` are re-exported at `logforth_append_opentelemetry::{opentelemetry, opentelemetry_sdk}` so callers do not need direct Cargo dependencies solely to name SDK traits or types.

Expand Down
8 changes: 8 additions & 0 deletions appenders/opentelemetry/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@
//! variants;
//! - `body` defaults to the formatted [`Record::payload`] string, or custom bytes/values produced
//! by [`MakeBody`] (such as [`MakeBodyLayout`]);
//! - `target` is set from [`Record::logger_name`] when present. Unnamed records use the configured
//! instrumentation scope name;
//! - `module_path`, `file`, `line`, and `column` are attached as attributes when present;
//! - [`Record::key_values`] and [`Diagnostic`] entries are mapped to typed [`AnyValue`] attributes,
//! with explicit record key-values taking precedence over diagnostics;
Expand Down Expand Up @@ -271,6 +273,12 @@ impl Append for OpentelemetryLog {
log_record.set_body(AnyValue::from(record.payload().to_string()));
}

if let Some(name) = record.logger_name_static() {
log_record.set_target(name);
} else if let Some(name) = record.logger_name() {
log_record.set_target(name.to_owned());
}

if let Some(module_path) = record.module_path_static() {
log_record.add_attribute("module_path", module_path);
} else if let Some(module_path) = record.module_path() {
Expand Down
Loading
Loading