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 @@ -67,7 +67,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 `Level::ALL` and `RecordBuilder::time` in `logforth-core` to enumerate all 24 severities and construct records with an explicit observed timestamp.
* Add `kv::ValueSerde` (`new`, `into_owned`, `try_into_owned`, `Deref`, `LogValue`, and `From<ValueSerde<'_, T>>` for `ValueOwned`, behind the `serde` feature) in `logforth-core` to capture `serde::Serialize` values as lazy structured fields or materialize them into `ValueOwned` snapshots without panicking.
* Add `ValueOwned::{from_serde, try_from_serde}` and `kv::ValueSerde` (`new`, `Deref`, and `LogValue`, behind the `serde` feature) in `logforth-core` to convert `serde::Serialize` values into `ValueOwned` snapshots without panicking or capture them as lazy structured fields.
* Add `kv::LogValue`, `Value::{owned, lazy_owned, to_owned}`, `Key::{as_str, to_owned}`, `KeyOwned::as_str`, `DebugValue::new`, `DisplayValue::new`, `KeyView::to_static_str`, and `ValueView::{is_none, to_bytes}` in `logforth-core`, and implement `From` on `kv::{KeyOwned, ValueOwned}` across scalars (including `NonZero*` integers), strings, byte slices, `Option<T>`, and borrowed `kv::{Key, KeyView, Value, ValueView}`.
* Add `ThreadLocalDiagnostic::scope` and `ThreadLocalDiagnosticGuard` in `logforth-core` for `!Send` RAII scoped thread-local diagnostics that restore shadowed entries on drop.
* Add `Error::message` and `LoggerBuilder::error_sink` in `logforth-core` (plus `starter_log::LogStarter::error_sink` in `logforth`) to inspect an error's own message and configure runtime error handling.
Expand Down
49 changes: 25 additions & 24 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -146,35 +146,36 @@ Runnable end-to-end scenarios live in the [`examples`](examples) workspace crate

`logforth` enables no optional features by default. Enable only the components your application uses:

| Category | APIs | Feature | Use |
| :---------- | :---------------------------------------- | :------------------------------- | :------------------------------------------------------------------------------- |
| Core APIs | [`Logger`], [`Record`], [`kv`], [`info!`] | *built-in* | Build loggers and emit structured records with key-value fields. |
| | [`ValueSerde`] | `serde` | Convert `serde::Serialize` values into [`kv`] fields and serialize [`kv`] types. |
| Appenders | [`Stdout`], [`Stderr`], [`Testing`] | *built-in* | Write formatted lines to standard output, standard error, or test output. |
| | [`File`] | `append-file` | Write to a single file or time- and size-rotated log files. |
| | [`Async`] | `append-async` | Offload downstream appender I/O onto a background worker thread. |
| | [`Journald`] | `append-journald` | Send structured log entries directly to `systemd-journald` on Unix. |
| | [`SocketSyslog`], [`PosixSyslog`] | `append-syslog` | Send logs to local or remote syslog daemons. |
| | [`OpentelemetryLog`] | `append-opentelemetry` | Export structured OpenTelemetry log batches with trace correlation. |
| | [`FastraceEvent`] | `append-fastrace` | Attach log records as events on active [`fastrace`] spans. |
| Layouts | [`PlainTextLayout`] | *built-in* | Minimal uncolored single-line text output. |
| | [`TextLayout`] | `layout-text` | Human-readable single-line text with timestamps and ANSI colors. |
| | [`LogfmtLayout`] | `layout-logfmt` | Single-line `key=value` [`logfmt`] output. |
| | [`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. |
| 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`. |
| | [`FastraceDiagnostic`] | `diagnostic-fastrace` | Attach trace and span IDs from active [`fastrace`] spans. |
| Bridges | [`starter_log`] | `starter-log` | Quick-start presets for installing Logforth as the global [`log`] backend. |
| | [`LogBridge`] | `bridge-log`, `bridge-log-serde` | Forward [`log`] records and `log::kv` fields into a `Logger`. |
| Category | APIs | Feature | Use |
| :---------- | :----------------------------------------- | :------------------------------- | :------------------------------------------------------------------------------- |
| Core APIs | [`Logger`], [`Record`], [`kv`], [`info!`] | *built-in* | Build loggers and emit structured records with key-value fields. |
| | [`ValueOwned::from_serde`], [`ValueSerde`] | `serde` | Convert `serde::Serialize` values into [`kv`] fields and serialize [`kv`] types. |
| Appenders | [`Stdout`], [`Stderr`], [`Testing`] | *built-in* | Write formatted lines to standard output, standard error, or test output. |
| | [`File`] | `append-file` | Write to a single file or time- and size-rotated log files. |
| | [`Async`] | `append-async` | Offload downstream appender I/O onto a background worker thread. |
| | [`Journald`] | `append-journald` | Send structured log entries directly to `systemd-journald` on Unix. |
| | [`SocketSyslog`], [`PosixSyslog`] | `append-syslog` | Send logs to local or remote syslog daemons. |
| | [`OpentelemetryLog`] | `append-opentelemetry` | Export structured OpenTelemetry log batches with trace correlation. |
| | [`FastraceEvent`] | `append-fastrace` | Attach log records as events on active [`fastrace`] spans. |
| Layouts | [`PlainTextLayout`] | *built-in* | Minimal uncolored single-line text output. |
| | [`TextLayout`] | `layout-text` | Human-readable single-line text with timestamps and ANSI colors. |
| | [`LogfmtLayout`] | `layout-logfmt` | Single-line `key=value` [`logfmt`] output. |
| | [`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. |
| 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`. |
| | [`FastraceDiagnostic`] | `diagnostic-fastrace` | Attach trace and span IDs from active [`fastrace`] spans. |
| Bridges | [`starter_log`] | `starter-log` | Quick-start presets for installing Logforth as the global [`log`] backend. |
| | [`LogBridge`] | `bridge-log`, `bridge-log-serde` | Forward [`log`] records and `log::kv` fields into a `Logger`. |

[`Logger`]: https://docs.rs/logforth/0.31.0/logforth/struct.Logger.html
[`Record`]: https://docs.rs/logforth/0.31.0/logforth/record/struct.Record.html
[`kv`]: https://docs.rs/logforth/0.31.0/logforth/kv/index.html
[`info!`]: https://docs.rs/logforth/0.31.0/logforth/macro.info.html
[`ValueOwned::from_serde`]: https://docs.rs/logforth/0.31.0/logforth/kv/struct.ValueOwned.html#method.from_serde
[`ValueSerde`]: https://docs.rs/logforth/0.31.0/logforth/kv/struct.ValueSerde.html
[`Stdout`]: https://docs.rs/logforth/0.31.0/logforth/append/struct.Stdout.html
[`Stderr`]: https://docs.rs/logforth/0.31.0/logforth/append/struct.Stderr.html
Expand Down
4 changes: 1 addition & 3 deletions bridges/log/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -243,8 +243,6 @@ mod kv {
use logforth_core::kv::Key;
use logforth_core::kv::Value;
use logforth_core::kv::ValueOwned;
#[cfg(feature = "serde")]
use logforth_core::kv::ValueSerde;

use crate::KEY_LOG_TARGET;

Expand Down Expand Up @@ -311,7 +309,7 @@ mod kv {
impl<'a> log::kv::VisitValue<'a> for ValueVisitor<'a> {
fn visit_any(&mut self, value: log::kv::Value) -> Result<(), log::kv::Error> {
#[cfg(feature = "serde")]
let owned = ValueSerde::new(&value).into_owned();
let owned = ValueOwned::from_serde(&value);
#[cfg(not(feature = "serde"))]
let owned = {
let mut buf = String::new();
Expand Down
2 changes: 1 addition & 1 deletion core/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ fn build_json_logger() -> Result<Logger, logforth_core::Error> {

`logforth-core` enables no features by default:

- `serde`: adds `kv::ValueSerde` to capture `serde::Serialize` values as lazy structured fields or `ValueOwned` snapshots, and implements `serde::Serialize` across `kv` types.
- `serde`: adds `ValueOwned::from_serde`, `ValueOwned::try_from_serde`, and `kv::ValueSerde` to capture `serde::Serialize` values as `ValueOwned` snapshots or lazy structured fields, and implements `serde::Serialize` across `kv` types.

## Documentation

Expand Down
6 changes: 3 additions & 3 deletions core/src/kv/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,9 @@
//! - **Owned snapshots** ([`KeyOwned`], [`ValueOwned`]) carry `'static + Send + Sync` structured
//! trees across thread boundaries and diagnostic scopes.
//!
//! With the `serde` feature enabled, `ValueSerde` adapts `serde::Serialize` values into lazy
//! borrowed [`Value`] fields or [`ValueOwned`] snapshots, and key-value carriers and views
//! implement `serde::Serialize`.
//! With the `serde` feature enabled, [`ValueOwned::from_serde`] and [`ValueOwned::try_from_serde`]
//! eagerly capture [`ValueOwned`] snapshots, while [`ValueSerde`] initializes structured fields
//! lazily. Key-value carriers and views implement `serde::Serialize`.
//!
//! Iteration over [`KeyValues`] and [`MapValue`] preserves insertion order, while point lookups via
//! [`KeyValues::get`] and [`MapValue::get`] resolve duplicate keys using last-entry-wins order.
Expand Down
70 changes: 34 additions & 36 deletions core/src/kv/value_serde.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,12 +24,42 @@ use crate::kv::Value;
use crate::kv::ValueOwned;
use crate::kv::ValueOwnedState;

impl ValueOwned {
/// Immediately serializes the borrowed value into an owned snapshot.
///
/// A serialization failure returns the string `"<serde error: {message}>"` instead of
/// panicking.
pub fn from_serde(value: &(impl serde::Serialize + ?Sized)) -> Self {
Self::try_from_serde(value)
.unwrap_or_else(|err| Self::str(format!("<serde error: {}>", err.message())))
}

/// Immediately serializes the borrowed value into a [`ValueOwned`] snapshot.
///
/// # Errors
///
/// Returns an error if the value fails to serialize.
///
/// # Examples
///
/// ```
/// use logforth_core::kv::ValueOwned;
///
/// let snapshot = ValueOwned::try_from_serde("ready").unwrap();
/// assert_eq!(snapshot.view().to_str(), Some("ready"));
/// ```
pub fn try_from_serde(value: &(impl serde::Serialize + ?Sized)) -> Result<Self, Error> {
value.serialize(ValueSerializer).map_err(|err| err.0)
}
}

/// A borrowed [`serde::Serialize`] value for lazy structured logging.
///
/// The first dereference serializes the value and caches the [`ValueOwned`] snapshot.
/// If serialization fails, the snapshot contains the string `"<serde error: {message}>"`.
/// When `T: Sync`, [`LogValue`] lets dispatches share this snapshot and defers
/// serialization until a dispatch inspects the field.
/// serialization until a dispatch inspects the field. For an eager snapshot, use
/// [`ValueOwned::from_serde`] or [`ValueOwned::try_from_serde`].
///
/// # Examples
///
Expand All @@ -40,7 +70,7 @@ use crate::kv::ValueOwnedState;
/// let field = ValueSerde::new(&[2, 3]);
/// let list = field.log_value().view().to_list().unwrap();
/// assert_eq!(list.iter().next().unwrap().to_i64(), Some(2));
/// assert_eq!(field.into_owned().view().to_list().unwrap().len(), 2);
/// assert_eq!(field.view().to_list().unwrap().len(), 2);
/// ```
pub struct ValueSerde<'a, T: serde::Serialize + ?Sized> {
value: &'a T,
Expand All @@ -55,40 +85,14 @@ impl<'a, T: serde::Serialize + ?Sized> ValueSerde<'a, T> {
cache: OnceLock::new(),
}
}

/// Consumes the adapter and moves out the cached snapshot, serializing the value if needed.
///
/// A serialization failure yields the string `"<serde error: {message}>"`.
pub fn into_owned(self) -> ValueOwned {
self.cache
.into_inner()
.unwrap_or_else(|| Self::serialize(self.value))
}

/// Consumes the adapter and serializes the borrowed value even if a snapshot is cached.
///
/// # Errors
///
/// Returns the error from this serialization attempt.
pub fn try_into_owned(self) -> Result<ValueOwned, Error> {
Self::try_serialize(self.value)
}

fn serialize(value: &T) -> ValueOwned {
Self::try_serialize(value)
.unwrap_or_else(|err| ValueOwned::str(format!("<serde error: {}>", err.message())))
}

fn try_serialize(value: &T) -> Result<ValueOwned, Error> {
value.serialize(ValueSerializer).map_err(|err| err.0)
}
}

impl<T: serde::Serialize + ?Sized> Deref for ValueSerde<'_, T> {
type Target = ValueOwned;

fn deref(&self) -> &Self::Target {
self.cache.get_or_init(|| Self::serialize(self.value))
self.cache
.get_or_init(|| ValueOwned::from_serde(self.value))
}
}

Expand All @@ -100,12 +104,6 @@ impl<T: serde::Serialize + ?Sized> fmt::Debug for ValueSerde<'_, T> {
}
}

impl<T: serde::Serialize + ?Sized> From<ValueSerde<'_, T>> for ValueOwned {
fn from(value: ValueSerde<'_, T>) -> Self {
value.into_owned()
}
}

impl<T: serde::Serialize + Sync + ?Sized> LogValue for ValueSerde<'_, T> {
fn log_value(&self) -> Value<'_> {
Value::lazy_owned(self)
Expand Down
2 changes: 1 addition & 1 deletion logforth/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@
//! | `layout-*` | Additional output formats. |
//! | `diagnostic-*` | Diagnostic context from traces or task-local values. |
//! | `filter-rustlog` | Filtering with `RUST_LOG` directives. |
//! | `serde` | `kv::ValueSerde` and `serde::Serialize` for [`kv`] types. |
//! | `serde` | `ValueOwned::from_serde`, `kv::ValueSerde`, and `serde::Serialize` for [`kv`] types. |
//! | `starter-log` | Starter pack: `starter_log`, `bridge-log`, `filter-rustlog`, text/JSON, and `append-file`. |
//! | `bridge-log` | `log` facade adapter (`LogBridge`). |
//! | `bridge-log-serde` | Structured `log/kv_serde` value bridging in `bridge-log`. |
Expand Down
5 changes: 2 additions & 3 deletions tests-integration/tests/bridge_test/log.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@ use log::kv::VisitSource;
use logforth::bridge::log::LogBridge;
use logforth::filter::rustlog::RustLogFilterBuilder;
use logforth::kv::ValueOwned;
use logforth::kv::ValueSerde;
use logforth::kv::ValueView;
use logforth::record::Level;
use logforth::record::LevelFilter;
Expand Down Expand Up @@ -302,8 +301,8 @@ fn fallible_kv_source_and_failing_display_never_panic() {
assert_eq!(fields.get("first").unwrap().to_u64(), Some(7));
});

assert!(ValueSerde::new(&FailingDisplay).try_into_owned().is_err());
let fallback = ValueSerde::new(&FailingDisplay).into_owned();
assert!(ValueOwned::try_from_serde(&FailingDisplay).is_err());
let fallback = ValueOwned::from_serde(&FailingDisplay);
bridge.log(
&log::Record::builder()
.key_values(&[("failure", Value::from_display(&FailingDisplay))])
Expand Down
Loading
Loading