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
2 changes: 1 addition & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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<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 `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 `kv::LogValue` (implemented across scalars, `NonZero*` / `Wrapping` / `Saturating` integers, strings, byte slices, paths, OS strings, network addresses, `Option<T>`, 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<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.
* 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`.
Expand Down
177 changes: 167 additions & 10 deletions core/src/kv/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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),
}
}
}

Expand Down Expand Up @@ -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<Target = ValueOwned> + Sync)),
}
Expand All @@ -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),
}
Expand Down Expand Up @@ -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(),
}
Expand Down Expand Up @@ -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
Expand All @@ -764,6 +791,12 @@ impl<T: LogValue + ?Sized> LogValue for &T {
}
}

impl<T: LogValue + ?Sized> LogValue for &mut T {
fn log_value(&self) -> Value<'_> {
(**self).log_value()
}
}

impl<T: LogValue + ?Sized> LogValue for Box<T> {
fn log_value(&self) -> Value<'_> {
(**self).log_value()
Expand Down Expand Up @@ -797,6 +830,18 @@ impl<T: LogValue> LogValue for Option<T> {
}
}

impl<T: LogValue> LogValue for Wrapping<T> {
fn log_value(&self) -> Value<'_> {
self.0.log_value()
}
}

impl<T: LogValue> LogValue for Saturating<T> {
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 {
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -980,6 +1100,40 @@ impl_value_owned_from!(Cow<'static, str>, |v| Self::str(v));
impl_value_owned_from!(Vec<u8>, |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<OsString> 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<PathBuf> for ValueOwned {
fn from(v: PathBuf) -> Self {
Self::from(v.into_os_string())
}
}

impl<T: Into<ValueOwned>> From<Wrapping<T>> for ValueOwned {
fn from(v: Wrapping<T>) -> Self {
v.0.into()
}
}

impl<T: Into<ValueOwned>> From<Saturating<T>> for ValueOwned {
fn from(v: Saturating<T>) -> Self {
v.0.into()
}
}

impl From<Value<'_>> for ValueOwned {
fn from(v: Value<'_>) -> Self {
v.to_owned()
Expand Down Expand Up @@ -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()),
},
}
}
}
Expand Down
Loading
Loading