From 93ae580df83c52a2f918e650e41d587ee56a42b4 Mon Sep 17 00:00:00 2001 From: tison Date: Thu, 3 Dec 2026 02:33:33 +0800 Subject: [PATCH] feat(core): implement LogValue and ValueOwned conversions for std types Structured logging call sites frequently pass filesystem paths, OS strings, network addresses, mutable references, and standard numeric wrappers directly in `["key" = value]` fields or owned diagnostic contexts. Without built-in `LogValue` and `From` implementations, callers had to convert paths and network addresses manually or wrap every site in `Value::display`. Implement `LogValue` in `logforth-core` for `&mut T`, `Wrapping`, `Saturating`, `OsStr`, `OsString`, `std::ffi::os_str::Display<'_>`, `Path`, `PathBuf`, `std::path::Display<'_>`, and the six `std::net` IP and socket address types, along with matching `From` implementations on `ValueOwned` for `OsString`, `PathBuf`, `std::net` addresses, `Wrapping`, and `Saturating`. Valid UTF-8 paths and OS strings borrow directly as `ValueView::BorrowedStr` (and move existing heap buffers into `ValueOwned` without reallocation), while non-UTF-8 inputs format lossily through `DisplayValue` without allocating on synchronous paths or failing serialization. Signed-off-by: tison --- CHANGELOG.md | 2 +- core/src/kv/mod.rs | 177 ++++++++++++++++++++++-- tests-integration/tests/core_test/kv.rs | 137 ++++++++++++++++++ 3 files changed, 305 insertions(+), 11 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 33b87087..7f67ea05 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -68,7 +68,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>` 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 `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`, and borrowed `kv::{Key, KeyView, Value, ValueView}`. +* Add `kv::LogValue` (implemented across scalars, `NonZero*` / `Wrapping` / `Saturating` integers, strings, byte slices, paths, OS strings, network addresses, `Option`, and `kv` containers), `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, strings, byte slices, `PathBuf`, `OsString`, network addresses, `Option`, 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. * Make `Logger` a pointer-sized `Clone` and `Default` handle over a shared pipeline, and 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`. diff --git a/core/src/kv/mod.rs b/core/src/kv/mod.rs index 38e4589c..3ebf258e 100644 --- a/core/src/kv/mod.rs +++ b/core/src/kv/mod.rs @@ -35,8 +35,20 @@ use std::borrow::Borrow; use std::borrow::Cow; +use std::ffi::OsStr; +use std::ffi::OsString; use std::fmt; +use std::net::IpAddr; +use std::net::Ipv4Addr; +use std::net::Ipv6Addr; +use std::net::SocketAddr; +use std::net::SocketAddrV4; +use std::net::SocketAddrV6; +use std::num::Saturating; +use std::num::Wrapping; use std::ops::Deref; +use std::path::Path; +use std::path::PathBuf; use std::rc::Rc; use std::slice; use std::sync::Arc; @@ -289,24 +301,33 @@ impl serde::Serialize for DebugValue<'_> { /// A value captured through its [`fmt::Display`] representation. #[derive(Clone, Copy)] -pub struct DisplayValue<'a>(&'a dyn fmt::Display); +pub struct DisplayValue<'a>(DisplayValueState<'a>); + +#[derive(Clone, Copy)] +enum DisplayValueState<'a> { + Display(&'a dyn fmt::Display), + OsStr(&'a OsStr), +} impl<'a> DisplayValue<'a> { /// Creates a new [`DisplayValue`] from a [`fmt::Display`] reference. pub const fn new(d: &'a dyn fmt::Display) -> Self { - Self(d) + Self(DisplayValueState::Display(d)) } } impl fmt::Debug for DisplayValue<'_> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - fmt::Display::fmt(&self.0, f) + fmt::Display::fmt(self, f) } } impl fmt::Display for DisplayValue<'_> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - fmt::Display::fmt(&self.0, f) + match self.0 { + DisplayValueState::Display(d) => fmt::Display::fmt(d, f), + DisplayValueState::OsStr(s) => fmt::Display::fmt(&s.display(), f), + } } } @@ -573,6 +594,7 @@ enum ValueState<'a> { Map(&'a [(Key<'a>, Value<'a>)]), Debug(&'a (dyn fmt::Debug + Sync)), Display(&'a (dyn fmt::Display + Sync)), + OsStr(&'a OsStr), Owned(&'a ValueOwned), LazyOwned(&'a (dyn Deref + Sync)), } @@ -594,6 +616,7 @@ impl fmt::Debug for ValueState<'_> { ValueState::Map(v) => v.fmt(f), ValueState::Debug(v) => fmt::Debug::fmt(v, f), ValueState::Display(v) => fmt::Display::fmt(v, f), + ValueState::OsStr(v) => fmt::Display::fmt(&v.display(), f), ValueState::Owned(v) => v.fmt(f), ValueState::LazyOwned(v) => (**v).fmt(f), } @@ -625,7 +648,10 @@ impl<'a> Value<'a> { ValueState::List(l) => ValueView::List(ListValue(ListValueState::Borrowed(l))), ValueState::Map(m) => ValueView::Map(MapValue(MapValueState::Borrowed(m))), ValueState::Debug(d) => ValueView::Debug(DebugValue(d)), - ValueState::Display(d) => ValueView::Display(DisplayValue(d)), + ValueState::Display(d) => { + ValueView::Display(DisplayValue(DisplayValueState::Display(d))) + } + ValueState::OsStr(s) => ValueView::Display(DisplayValue(DisplayValueState::OsStr(s))), ValueState::Owned(o) => o.view(), ValueState::LazyOwned(v) => (**v).view(), } @@ -745,10 +771,11 @@ impl<'a> Value<'a> { /// A value that can be captured as a borrowed structured [`Value`] for logging. /// /// Native logging macros use this trait to borrow the value in a field such as `["key" = value]`. -/// Custom types can expose a scalar with [`Value::str`] or [`Value::u64`], borrow a snapshot with -/// [`Value::owned`] or [`Value::lazy_owned`], or defer formatting with [`Value::debug`] or -/// [`Value::display`]. With the `serde` feature, `kv::ValueSerde` provides this trait for a -/// borrowed `serde::Serialize + Sync` value. +/// Built-in implementations cover scalars, strings, byte slices, paths, OS strings, and network +/// addresses. Custom types can expose a scalar with [`Value::str`] or [`Value::u64`], borrow a +/// snapshot with [`Value::owned`] or [`Value::lazy_owned`], or defer formatting with +/// [`Value::debug`] or [`Value::display`]. With the `serde` feature, `kv::ValueSerde` provides this +/// trait for a borrowed `serde::Serialize + Sync` value. /// /// Capturing a string through [`LogValue::log_value`] ties its borrow to `&self` and yields /// [`ValueView::BorrowedStr`]. Pass [`Value::static_str`] explicitly to preserve a string's @@ -764,6 +791,12 @@ impl LogValue for &T { } } +impl LogValue for &mut T { + fn log_value(&self) -> Value<'_> { + (**self).log_value() + } +} + impl LogValue for Box { fn log_value(&self) -> Value<'_> { (**self).log_value() @@ -797,6 +830,18 @@ impl LogValue for Option { } } +impl LogValue for Wrapping { + fn log_value(&self) -> Value<'_> { + self.0.log_value() + } +} + +impl LogValue for Saturating { + fn log_value(&self) -> Value<'_> { + self.0.log_value() + } +} + macro_rules! impl_scalar_log_value { ($ty:ty, |$v:ident| $expr:expr) => { impl LogValue for $ty { @@ -850,6 +895,81 @@ impl LogValue for String { } } +impl LogValue for OsStr { + fn log_value(&self) -> Value<'_> { + match self.to_str() { + Some(s) => Value::str(s), + None => Value(ValueState::OsStr(self)), + } + } +} + +impl LogValue for OsString { + fn log_value(&self) -> Value<'_> { + self.as_os_str().log_value() + } +} + +impl LogValue for std::ffi::os_str::Display<'_> { + fn log_value(&self) -> Value<'_> { + Value::display(self) + } +} + +impl LogValue for Path { + fn log_value(&self) -> Value<'_> { + self.as_os_str().log_value() + } +} + +impl LogValue for PathBuf { + fn log_value(&self) -> Value<'_> { + self.as_path().log_value() + } +} + +impl LogValue for std::path::Display<'_> { + fn log_value(&self) -> Value<'_> { + Value::display(self) + } +} + +impl LogValue for IpAddr { + fn log_value(&self) -> Value<'_> { + Value::display(self) + } +} + +impl LogValue for Ipv4Addr { + fn log_value(&self) -> Value<'_> { + Value::display(self) + } +} + +impl LogValue for Ipv6Addr { + fn log_value(&self) -> Value<'_> { + Value::display(self) + } +} + +impl LogValue for SocketAddr { + fn log_value(&self) -> Value<'_> { + Value::display(self) + } +} + +impl LogValue for SocketAddrV4 { + fn log_value(&self) -> Value<'_> { + Value::display(self) + } +} + +impl LogValue for SocketAddrV6 { + fn log_value(&self) -> Value<'_> { + Value::display(self) + } +} + impl LogValue for [u8] { fn log_value(&self) -> Value<'_> { Value::bytes(self) @@ -980,6 +1100,40 @@ impl_value_owned_from!(Cow<'static, str>, |v| Self::str(v)); impl_value_owned_from!(Vec, |v| Self::bytes(v)); impl_value_owned_from!(Box<[u8]>, |v| Self::bytes(v)); +impl_value_owned_from!(IpAddr, |v| Self::str(v.to_string())); +impl_value_owned_from!(Ipv4Addr, |v| Self::str(v.to_string())); +impl_value_owned_from!(Ipv6Addr, |v| Self::str(v.to_string())); +impl_value_owned_from!(SocketAddr, |v| Self::str(v.to_string())); +impl_value_owned_from!(SocketAddrV4, |v| Self::str(v.to_string())); +impl_value_owned_from!(SocketAddrV6, |v| Self::str(v.to_string())); + +impl From for ValueOwned { + fn from(v: OsString) -> Self { + match v.into_string() { + Ok(s) => Self::str(s), + Err(os) => Self::str(os.to_string_lossy().into_owned()), + } + } +} + +impl From for ValueOwned { + fn from(v: PathBuf) -> Self { + Self::from(v.into_os_string()) + } +} + +impl> From> for ValueOwned { + fn from(v: Wrapping) -> Self { + v.0.into() + } +} + +impl> From> for ValueOwned { + fn from(v: Saturating) -> Self { + v.0.into() + } +} + impl From> for ValueOwned { fn from(v: Value<'_>) -> Self { v.to_owned() @@ -1213,7 +1367,10 @@ impl ValueView<'_> { Self::List(l) => ValueOwned::list(l.iter().map(|v| v.to_owned())), Self::Map(m) => ValueOwned::map(m.iter().map(|(k, v)| (k.to_owned(), v.to_owned()))), Self::Debug(d) => ValueOwned::str(format!("{d:?}")), - Self::Display(d) => ValueOwned::str(d.to_string()), + Self::Display(d) => match d.0 { + DisplayValueState::Display(d) => ValueOwned::str(d.to_string()), + DisplayValueState::OsStr(s) => ValueOwned::str(s.to_string_lossy().into_owned()), + }, } } } diff --git a/tests-integration/tests/core_test/kv.rs b/tests-integration/tests/core_test/kv.rs index 65946ab4..d513cf83 100644 --- a/tests-integration/tests/core_test/kv.rs +++ b/tests-integration/tests/core_test/kv.rs @@ -15,10 +15,18 @@ use std::borrow::Cow; use std::collections::BTreeMap; use std::collections::HashMap; +use std::ffi::OsStr; +use std::ffi::OsString; +use std::net::IpAddr; +use std::net::SocketAddr; use std::num::NonZeroI16; use std::num::NonZeroI128; use std::num::NonZeroU32; use std::num::NonZeroU128; +use std::num::Saturating; +use std::num::Wrapping; +use std::path::Path; +use std::path::PathBuf; use std::rc::Rc; use std::sync::Arc; use std::sync::atomic::AtomicUsize; @@ -165,6 +173,135 @@ fn log_value_and_value_owned_project_scalars_containers_and_wrappers() { assert_eq!(items[1].to_static_str(), Some("two")); } +#[test] +fn std_types_project_into_log_value_and_value_owned() { + assert_eq!(size_of::>(), size_of::>()); + #[cfg(target_pointer_width = "64")] + assert_eq!(size_of::>(), 32); + + let path = Path::new("static/path"); + let mut path_buf = PathBuf::from("owned/path"); + let cow = Cow::Borrowed(path); + let os = OsStr::new("os"); + let mut text = String::from("text"); + let os_string = OsString::from(os); + for (value, expected) in [ + (path.log_value(), "static/path"), + (path_buf.log_value(), "owned/path"), + (cow.log_value(), "static/path"), + (os.log_value(), "os"), + (os_string.log_value(), "os"), + (LogValue::log_value(&text.as_mut_str()), "text"), + ] { + assert!(matches!(value.view(), ValueView::BorrowedStr(s) if s == expected)); + } + assert_eq!( + LogValue::log_value(&&mut path_buf).view().to_str(), + Some("owned/path") + ); + assert_eq!(ValueOwned::from(os_string).view().to_str(), Some("os")); + assert_eq!( + ValueOwned::from(path_buf).view().to_str(), + Some("owned/path") + ); + assert_eq!( + ValueOwned::from(Cow::Owned(String::from("owned"))) + .view() + .to_str(), + Some("owned") + ); + for (value, expected) in [ + (path.display().log_value(), "static/path"), + (os.display().log_value(), "os"), + ] { + assert_eq!(value.view().to_display().unwrap().to_string(), expected); + } + + #[cfg(any(unix, windows))] + { + #[cfg(unix)] + let (os, expected) = { + use std::os::unix::ffi::OsStrExt; + + ( + OsStr::from_bytes(b"/tmp/\xff/segment"), + "/tmp/\u{fffd}/segment", + ) + }; + #[cfg(windows)] + let invalid = { + use std::os::windows::ffi::OsStringExt; + + OsString::from_wide(&[0x0061, 0xD800]) + }; + #[cfg(windows)] + let (os, expected) = (invalid.as_os_str(), "a\u{fffd}"); + + let path = Path::new(os); + let fields = [ + (Key::new("path"), path.log_value()), + (Key::new("os"), os.log_value()), + ]; + let record = RecordBuilder::new().key_values(fields.as_slice()).build(); + let serialized = ValueSerde::new(&record.key_values()) + .try_into_owned() + .unwrap(); + let map = serialized.view().to_map().unwrap(); + for (key, view) in record.key_values() { + assert!(view.to_str().is_none()); + assert_eq!(view.to_display().unwrap().to_string(), expected); + assert_eq!(view.to_owned().view().to_str(), Some(expected)); + assert_eq!(map.get(key.as_str()).unwrap().to_str(), Some(expected)); + } + assert_eq!( + ValueOwned::from(path.to_path_buf()).view().to_str(), + Some(expected) + ); + } + + let ip = IpAddr::from([127, 0, 0, 1]); + let socket = SocketAddr::new(ip, 8080); + let wrapped = Wrapping(7_u32); + let saturated = Saturating(-3_i16); + let sink = RecordingAppender::default(); + let logger = logforth_core::builder() + .dispatch(|d| d.append(sink.clone())) + .build(); + logforth_core::info!( + logger, + [ + "ip" = ip, + "socket" = socket, + "wrapped" = wrapped, + "saturated" = saturated + ], + "network" + ); + sink.events()[0].record.with(|r| { + let fields = r.key_values(); + assert_eq!(fields.get("ip").unwrap().to_str(), Some("127.0.0.1")); + assert_eq!( + fields.get("socket").unwrap().to_str(), + Some("127.0.0.1:8080") + ); + assert!(matches!(fields.get("wrapped"), Some(ValueView::U64(7)))); + assert!(matches!(fields.get("saturated"), Some(ValueView::I64(-3)))); + }); + assert_eq!(ValueOwned::from(ip).view().to_str(), Some("127.0.0.1")); + assert_eq!( + ValueOwned::from(socket).view().to_str(), + Some("127.0.0.1:8080") + ); + assert!(matches!( + ValueOwned::from(wrapped).view(), + ValueView::U64(7) + )); + assert!(matches!( + ValueOwned::from(saturated).view(), + ValueView::I64(-3) + )); +} + #[test] fn value_view_integer_accessors_convert_losslessly_and_reject_out_of_range_values() { const {