diff --git a/CHANGELOG.md b/CHANGELOG.md index cd0f165e..eb3ca844 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,10 @@ All significant changes to this project will be documented in this file. ## Unreleased +### New features + +* Add `kv::lazy` (`kv::ValueLazy`) and `kv::serde` (behind the `serde` feature) in `logforth-core` and `logforth` to defer computing and memoize structured fields and formatted payload values on first inspection. + ## v0.31.0 | Crate | Version | diff --git a/core/README.md b/core/README.md index 013ac73a..18631072 100644 --- a/core/README.md +++ b/core/README.md @@ -79,7 +79,7 @@ fn build_json_logger() -> Result { `logforth-core` enables no features by default: -- `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. +- `serde`: adds `ValueOwned::from_serde`, `ValueOwned::try_from_serde`, `kv::serde`, and `kv::ValueSerde` to capture `serde::Serialize` values as `ValueOwned` snapshots or lazy structured fields, and implements `serde::Serialize` across `kv` types. ## Documentation diff --git a/core/src/kv/mod.rs b/core/src/kv/mod.rs index daecaf1d..108b9137 100644 --- a/core/src/kv/mod.rs +++ b/core/src/kv/mod.rs @@ -23,9 +23,15 @@ //! - **Owned snapshots** ([`KeyOwned`], [`ValueOwned`]) carry `'static + Send + Sync` structured //! trees across thread boundaries and diagnostic scopes. //! -//! 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`. +//! [`lazy`] wraps a closure in a [`ValueLazy`] for fields or message arguments that are expensive +//! to compute. +#![cfg_attr( + feature = "serde", + doc = " +With the `serde` feature, [`serde()`] creates a [`ValueSerde`] that serializes on first access. +[`ValueOwned::from_serde`] and [`ValueOwned::try_from_serde`] capture snapshots immediately. +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. @@ -44,10 +50,16 @@ use std::sync::Arc; use crate::Error; use crate::str::RefStr; +mod value_lazy; +pub use self::value_lazy::ValueLazy; +pub use self::value_lazy::lazy; + #[cfg(feature = "serde")] mod value_serde; #[cfg(feature = "serde")] pub use self::value_serde::ValueSerde; +#[cfg(feature = "serde")] +pub use self::value_serde::serde; /// A visitor that walks structured key-value pairs. /// @@ -81,8 +93,8 @@ impl fmt::Display for Key<'_> { } #[cfg(feature = "serde")] -impl serde::Serialize for Key<'_> { - fn serialize(&self, serializer: S) -> Result { +impl ::serde::Serialize for Key<'_> { + fn serialize(&self, serializer: S) -> Result { serializer.serialize_str(self.as_str()) } } @@ -180,8 +192,8 @@ impl fmt::Display for KeyOwned { } #[cfg(feature = "serde")] -impl serde::Serialize for KeyOwned { - fn serialize(&self, serializer: S) -> Result { +impl ::serde::Serialize for KeyOwned { + fn serialize(&self, serializer: S) -> Result { serializer.serialize_str(self.as_str()) } } @@ -226,8 +238,8 @@ impl fmt::Display for KeyView<'_> { } #[cfg(feature = "serde")] -impl serde::Serialize for KeyView<'_> { - fn serialize(&self, serializer: S) -> Result { +impl ::serde::Serialize for KeyView<'_> { + fn serialize(&self, serializer: S) -> Result { serializer.serialize_str(self.as_str()) } } @@ -278,8 +290,8 @@ impl fmt::Display for DebugValue<'_> { } #[cfg(feature = "serde")] -impl serde::Serialize for DebugValue<'_> { - fn serialize(&self, serializer: S) -> Result { +impl ::serde::Serialize for DebugValue<'_> { + fn serialize(&self, serializer: S) -> Result { serializer.collect_str(self) } } @@ -308,8 +320,8 @@ impl fmt::Display for DisplayValue<'_> { } #[cfg(feature = "serde")] -impl serde::Serialize for DisplayValue<'_> { - fn serialize(&self, serializer: S) -> Result { +impl ::serde::Serialize for DisplayValue<'_> { + fn serialize(&self, serializer: S) -> Result { serializer.collect_str(self) } } @@ -345,8 +357,8 @@ impl fmt::Debug for ListValue<'_> { } #[cfg(feature = "serde")] -impl serde::Serialize for ListValue<'_> { - fn serialize(&self, serializer: S) -> Result { +impl ::serde::Serialize for ListValue<'_> { + fn serialize(&self, serializer: S) -> Result { serializer.collect_seq(self.iter()) } } @@ -442,8 +454,8 @@ impl fmt::Debug for MapValue<'_> { } #[cfg(feature = "serde")] -impl serde::Serialize for MapValue<'_> { - fn serialize(&self, serializer: S) -> Result { +impl ::serde::Serialize for MapValue<'_> { + fn serialize(&self, serializer: S) -> Result { self.0.serialize(serializer) } } @@ -558,8 +570,8 @@ impl fmt::Debug for ValueState<'_> { } #[cfg(feature = "serde")] -impl serde::Serialize for Value<'_> { - fn serialize(&self, serializer: S) -> Result { +impl ::serde::Serialize for Value<'_> { + fn serialize(&self, serializer: S) -> Result { self.view().serialize(serializer) } } @@ -680,7 +692,11 @@ impl<'a> Value<'a> { /// Creates a value borrowing a lazily initialized [`ValueOwned`]. /// /// Inspection dereferences the source, which can be any `Deref + Sync` - /// type such as `std::sync::LazyLock`. + /// type, including the [`ValueLazy`] returned by [`lazy`] with a `Send` initializer. + #[cfg_attr( + feature = "serde", + doc = "For serializable `Sync` values, [`serde()`] provides a [`ValueSerde`] source." + )] /// /// # Examples /// @@ -704,8 +720,11 @@ impl<'a> Value<'a> { /// 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. +/// [`Value::display`]. [`lazy`] creates a [`ValueLazy`] field from a `Send` initializer. +#[cfg_attr( + feature = "serde", + doc = "[`serde()`] creates a [`ValueSerde`] field from 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 @@ -959,8 +978,8 @@ impl> From> for ValueOwned { } #[cfg(feature = "serde")] -impl serde::Serialize for ValueOwned { - fn serialize(&self, serializer: S) -> Result { +impl ::serde::Serialize for ValueOwned { + fn serialize(&self, serializer: S) -> Result { self.view().serialize(serializer) } } @@ -1130,8 +1149,8 @@ impl fmt::Display for ValueView<'_> { } #[cfg(feature = "serde")] -impl serde::Serialize for ValueView<'_> { - fn serialize(&self, serializer: S) -> Result { +impl ::serde::Serialize for ValueView<'_> { + fn serialize(&self, serializer: S) -> Result { match &self { ValueView::None => serializer.serialize_none(), ValueView::BorrowedStr(v) => serializer.serialize_str(v), @@ -1340,8 +1359,8 @@ impl fmt::Debug for KeyValues<'_> { } #[cfg(feature = "serde")] -impl serde::Serialize for KeyValues<'_> { - fn serialize(&self, serializer: S) -> Result { +impl ::serde::Serialize for KeyValues<'_> { + fn serialize(&self, serializer: S) -> Result { serializer.collect_map(self.iter()) } } diff --git a/core/src/kv/value_lazy.rs b/core/src/kv/value_lazy.rs new file mode 100644 index 00000000..82a11717 --- /dev/null +++ b/core/src/kv/value_lazy.rs @@ -0,0 +1,142 @@ +// Copyright 2024 FastLabs Developers +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +use std::fmt; +use std::ops::Deref; +use std::sync::Mutex; +use std::sync::OnceLock; +use std::sync::PoisonError; + +use crate::kv::LogValue; +use crate::kv::Value; +use crate::kv::ValueOwned; + +/// A lazily initialized, owned log value shared by all readers of the wrapper. +/// +/// The first dereference or display computes the value. Subsequent reads reuse it. +/// Debug formatting shows the cached value or `` without running the closure. +/// With a `Send` initializer, the wrapper also implements [`LogValue`] for structured fields. +/// +/// # Panics +/// +/// If initialization panics, each subsequent dereference or display also panics. +/// +/// # Examples +/// +/// ``` +/// use logforth_core::kv::ValueLazy; +/// +/// let field = ValueLazy::new(|| String::from("ready")); +/// assert_eq!(field.to_string(), "ready"); +/// assert_eq!(field.view().to_str(), Some("ready")); +/// ``` +pub struct ValueLazy { + init: Mutex>, + cache: OnceLock, +} + +impl ValueLazy { + /// Creates a value that runs `init` at most once, on first access. + /// + /// # Examples + /// + /// ``` + /// use logforth_core::kv::ValueLazy; + /// + /// let attempts = ValueLazy::new(|| 3_u64); + /// assert_eq!(attempts.view().to_u64(), Some(3)); + /// ``` + pub const fn new(init: F) -> Self + where + F: FnOnce() -> T, + T: Into, + { + Self { + init: Mutex::new(Some(init)), + cache: OnceLock::new(), + } + } +} + +/// Defers computing a structured field or message argument until its value is needed. +/// +/// Each dispatch that reads the value shares the result of the first initialization. +/// See [`ValueLazy`] for behavior if initialization panics. +/// +/// # Examples +/// +/// ``` +/// use logforth_core::kv; +/// +/// let elapsed = kv::lazy(|| 42_u64); +/// assert_eq!(format!("{elapsed} ms"), "42 ms"); +/// ``` +pub const fn lazy(init: F) -> ValueLazy +where + F: FnOnce() -> T, + T: Into, +{ + ValueLazy::new(init) +} + +impl Deref for ValueLazy +where + F: FnOnce() -> T, + T: Into, +{ + type Target = ValueOwned; + + fn deref(&self) -> &Self::Target { + self.cache.get_or_init(|| { + let init = self + .init + .lock() + .unwrap_or_else(PoisonError::into_inner) + .take() + .expect("ValueLazy instance has previously been poisoned"); + init().into() + }) + } +} + +impl fmt::Debug for ValueLazy { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let mut debug = f.debug_struct("ValueLazy"); + match self.cache.get() { + Some(value) => debug.field("value", value), + None => debug.field("value", &format_args!("")), + } + .finish() + } +} + +impl fmt::Display for ValueLazy +where + F: FnOnce() -> T, + T: Into, +{ + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + fmt::Display::fmt(&self.view(), f) + } +} + +impl LogValue for ValueLazy +where + F: FnOnce() -> T + Send, + T: Into, +{ + fn log_value(&self) -> Value<'_> { + Value::lazy_owned(self) + } +} diff --git a/core/src/kv/value_serde.rs b/core/src/kv/value_serde.rs index 8e94cee4..eac96a02 100644 --- a/core/src/kv/value_serde.rs +++ b/core/src/kv/value_serde.rs @@ -29,7 +29,7 @@ impl ValueOwned { /// /// A serialization failure returns the string `""` instead of /// panicking. - pub fn from_serde(value: &(impl serde::Serialize + ?Sized)) -> Self { + pub fn from_serde(value: &(impl ::serde::Serialize + ?Sized)) -> Self { Self::try_from_serde(value) .unwrap_or_else(|err| Self::str(format!("", err.message()))) } @@ -48,12 +48,26 @@ impl 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 { + pub fn try_from_serde(value: &(impl ::serde::Serialize + ?Sized)) -> Result { value.serialize(ValueSerializer).map_err(|err| err.0) } } -/// A borrowed [`serde::Serialize`] value for lazy structured logging. +/// Borrows a serializable value and caches its owned snapshot on first inspection. +/// +/// # Examples +/// +/// ``` +/// use logforth_core::kv; +/// +/// let field = kv::serde(&[2, 3]); +/// assert_eq!(field.view().to_string(), "[2, 3]"); +/// ``` +pub const fn serde(value: &T) -> ValueSerde<'_, T> { + ValueSerde::new(value) +} + +/// A borrowed [`serde::Serialize`](::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 `""`. @@ -72,12 +86,12 @@ impl ValueOwned { /// assert_eq!(list.iter().next().unwrap().to_i64(), Some(2)); /// assert_eq!(field.view().to_list().unwrap().len(), 2); /// ``` -pub struct ValueSerde<'a, T: serde::Serialize + ?Sized> { +pub struct ValueSerde<'a, T: ::serde::Serialize + ?Sized> { value: &'a T, cache: OnceLock, } -impl<'a, T: serde::Serialize + ?Sized> ValueSerde<'a, T> { +impl<'a, T: ::serde::Serialize + ?Sized> ValueSerde<'a, T> { /// Creates an adapter that borrows the value without serializing it. pub const fn new(value: &'a T) -> Self { Self { @@ -87,7 +101,7 @@ impl<'a, T: serde::Serialize + ?Sized> ValueSerde<'a, T> { } } -impl Deref for ValueSerde<'_, T> { +impl Deref for ValueSerde<'_, T> { type Target = ValueOwned; fn deref(&self) -> &Self::Target { @@ -96,7 +110,7 @@ impl Deref for ValueSerde<'_, T> { } } -impl fmt::Debug for ValueSerde<'_, T> { +impl fmt::Debug for ValueSerde<'_, T> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("ValueSerde") .field("value", &"") @@ -104,7 +118,7 @@ impl fmt::Debug for ValueSerde<'_, T> { } } -impl LogValue for ValueSerde<'_, T> { +impl LogValue for ValueSerde<'_, T> { fn log_value(&self) -> Value<'_> { Value::lazy_owned(self) } @@ -121,7 +135,7 @@ impl fmt::Display for ValueError { impl std::error::Error for ValueError {} -impl serde::ser::Error for ValueError { +impl ::serde::ser::Error for ValueError { fn custom(msg: T) -> Self { Self(Error::new(msg.to_string())) } @@ -152,7 +166,7 @@ struct ValueSerializeStructVariant { entries: Vec<(KeyOwned, ValueOwned)>, } -impl serde::Serializer for ValueSerializer { +impl ::serde::Serializer for ValueSerializer { type Ok = ValueOwned; type Error = ValueError; type SerializeSeq = ValueSerializeSeq; @@ -231,7 +245,7 @@ impl serde::Serializer for ValueSerializer { Ok(ValueOwned::none()) } - fn serialize_some( + fn serialize_some( self, value: &T, ) -> Result { @@ -255,7 +269,7 @@ impl serde::Serializer for ValueSerializer { Ok(ValueOwned::str(variant)) } - fn serialize_newtype_struct( + fn serialize_newtype_struct( self, _: &'static str, value: &T, @@ -263,7 +277,7 @@ impl serde::Serializer for ValueSerializer { value.serialize(self) } - fn serialize_newtype_variant( + fn serialize_newtype_variant( self, _: &'static str, _: u32, @@ -343,16 +357,16 @@ impl serde::Serializer for ValueSerializer { fn collect_str(self, value: &T) -> Result { let mut buf = String::new(); - write!(&mut buf, "{value}").map_err(serde::ser::Error::custom)?; + write!(&mut buf, "{value}").map_err(::serde::ser::Error::custom)?; Ok(ValueOwned::str(buf)) } } -impl serde::ser::SerializeSeq for ValueSerializeSeq { +impl ::serde::ser::SerializeSeq for ValueSerializeSeq { type Ok = ValueOwned; type Error = ValueError; - fn serialize_element( + fn serialize_element( &mut self, value: &T, ) -> Result<(), Self::Error> { @@ -365,11 +379,11 @@ impl serde::ser::SerializeSeq for ValueSerializeSeq { } } -impl serde::ser::SerializeTuple for ValueSerializeSeq { +impl ::serde::ser::SerializeTuple for ValueSerializeSeq { type Ok = ValueOwned; type Error = ValueError; - fn serialize_element( + fn serialize_element( &mut self, value: &T, ) -> Result<(), Self::Error> { @@ -382,11 +396,11 @@ impl serde::ser::SerializeTuple for ValueSerializeSeq { } } -impl serde::ser::SerializeTupleStruct for ValueSerializeSeq { +impl ::serde::ser::SerializeTupleStruct for ValueSerializeSeq { type Ok = ValueOwned; type Error = ValueError; - fn serialize_field( + fn serialize_field( &mut self, value: &T, ) -> Result<(), Self::Error> { @@ -399,11 +413,11 @@ impl serde::ser::SerializeTupleStruct for ValueSerializeSeq { } } -impl serde::ser::SerializeTupleVariant for ValueSerializeTupleVariant { +impl ::serde::ser::SerializeTupleVariant for ValueSerializeTupleVariant { type Ok = ValueOwned; type Error = ValueError; - fn serialize_field( + fn serialize_field( &mut self, value: &T, ) -> Result<(), Self::Error> { @@ -419,11 +433,14 @@ impl serde::ser::SerializeTupleVariant for ValueSerializeTupleVariant { } } -impl serde::ser::SerializeMap for ValueSerializeMap { +impl ::serde::ser::SerializeMap for ValueSerializeMap { type Ok = ValueOwned; type Error = ValueError; - fn serialize_key(&mut self, key: &T) -> Result<(), Self::Error> { + fn serialize_key( + &mut self, + key: &T, + ) -> Result<(), Self::Error> { let key = match key.serialize(ValueSerializer)?.0 { ValueOwnedState::Str(s) => KeyOwned(s), other => KeyOwned::new(ValueOwned(other).view().to_string()), @@ -432,14 +449,14 @@ impl serde::ser::SerializeMap for ValueSerializeMap { Ok(()) } - fn serialize_value( + fn serialize_value( &mut self, value: &T, ) -> Result<(), Self::Error> { let key = self .key .take() - .ok_or_else(|| serde::ser::Error::custom("missing map key"))?; + .ok_or_else(|| ::serde::ser::Error::custom("missing map key"))?; self.entries.push((key, value.serialize(ValueSerializer)?)); Ok(()) } @@ -449,11 +466,11 @@ impl serde::ser::SerializeMap for ValueSerializeMap { } } -impl serde::ser::SerializeStruct for ValueSerializeStruct { +impl ::serde::ser::SerializeStruct for ValueSerializeStruct { type Ok = ValueOwned; type Error = ValueError; - fn serialize_field( + fn serialize_field( &mut self, key: &'static str, value: &T, @@ -468,11 +485,11 @@ impl serde::ser::SerializeStruct for ValueSerializeStruct { } } -impl serde::ser::SerializeStructVariant for ValueSerializeStructVariant { +impl ::serde::ser::SerializeStructVariant for ValueSerializeStructVariant { type Ok = ValueOwned; type Error = ValueError; - fn serialize_field( + fn serialize_field( &mut self, key: &'static str, value: &T, diff --git a/examples/src/redact_layout.rs b/examples/src/redact_layout.rs index f13eca06..93a943d3 100644 --- a/examples/src/redact_layout.rs +++ b/examples/src/redact_layout.rs @@ -14,7 +14,7 @@ //! How to log `serde` structs and redact sensitive fields in a custom `Layout`? //! -//! Pass `ValueSerde::new(&attempt)` to borrow a `serde::Serialize` struct as a structured log +//! Pass `kv::serde(&attempt)` to borrow a `serde::Serialize` struct as a structured log //! field, and wrap an inner `Layout` in a custom `Layout` that walks record fields and diagnostics //! via `ValueView` to redact sensitive keys across nested maps and lists before formatting. @@ -25,11 +25,11 @@ use logforth::Error; use logforth::Layout; use logforth::append::Stdout; use logforth::diagnostic::StaticDiagnostic; +use logforth::kv; use logforth::kv::KeyOwned; use logforth::kv::KeyValues; use logforth::kv::KeyView; use logforth::kv::ValueOwned; -use logforth::kv::ValueSerde; use logforth::kv::ValueView; use logforth::kv::Visitor; use logforth::layout::JsonLayout; @@ -144,7 +144,7 @@ fn main() { logforth::info!( logger, [ - "attempt" = ValueSerde::new(&attempt), + "attempt" = kv::serde(&attempt), "password" = "request-password" ], "Webhook delivery attempted" diff --git a/logforth/src/lib.rs b/logforth/src/lib.rs index 04f6b2dd..50401c18 100644 --- a/logforth/src/lib.rs +++ b/logforth/src/lib.rs @@ -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` | `ValueOwned::from_serde`, `kv::ValueSerde`, and `serde::Serialize` for [`kv`] types. | +//! | `serde` | `ValueOwned::from_serde`, `kv::serde`, `kv::ValueSerde`, and `serde::Serialize` for [`kv`]. | //! | `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`. | diff --git a/tests-integration/tests/core_test/kv.rs b/tests-integration/tests/core_test/kv.rs index 57c3a0f9..bd432f59 100644 --- a/tests-integration/tests/core_test/kv.rs +++ b/tests-integration/tests/core_test/kv.rs @@ -24,6 +24,7 @@ use std::sync::Arc; use std::sync::atomic::AtomicUsize; use std::sync::atomic::Ordering; +use logforth::kv; use logforth_core::Diagnostic; use logforth_core::Error; use logforth_core::Filter; @@ -366,6 +367,87 @@ impl Serialize for StatusBytes { struct FallibleSerialize; +#[derive(Debug)] +struct RejectDrop; + +impl Filter for RejectDrop { + fn filter_level(&self, _: Level) -> FilterResult { + FilterResult::Neutral + } + + fn filter(&self, record: &Record, _: &dyn Diagnostic) -> FilterResult { + if record.payload().as_str() == Some("drop") { + FilterResult::Reject + } else { + FilterResult::Neutral + } + } +} + +#[test] +fn lazy_skips_rejected_records_and_memoizes_fields_and_payloads() { + let sink = RecordingAppender::default(); + let logger = logforth_core::builder() + .dispatch(|d| { + d.filter(LevelFilter::Equal(Level::Warn)) + .append(sink.clone()) + }) + .dispatch(|d| { + d.filter(LevelFilter::MoreSevereEqual(Level::Info)) + .filter(RejectDrop) + .append(sink.clone()) + }) + .build(); + + let calls = AtomicUsize::new(0); + let count = || calls.fetch_add(1, Ordering::Relaxed); + assert!(!logger.enabled(Level::Debug)); + logforth_core::debug!(logger, ["k" = kv::lazy(count)], "{}", kv::lazy(count)); + assert_eq!(calls.load(Ordering::Relaxed), 0); + + assert!(logger.enabled(Level::Info)); + logforth_core::info!(logger, ["k" = kv::lazy(count)], "drop"); + assert!(sink.events().is_empty()); + assert_eq!(calls.load(Ordering::Relaxed), 0); + + let payload_calls = AtomicUsize::new(0); + logforth_core::warn!( + logger, + ["k" = kv::lazy(count)], + "{}", + kv::lazy(|| payload_calls.fetch_add(1, Ordering::Relaxed)) + ); + let events = sink.events(); + assert_eq!(events.len(), 2); + for event in events { + event.record.with(|record| { + assert_eq!(record.key_values().get("k").unwrap().to_u64(), Some(0)); + assert_eq!(record.payload().to_string(), "0"); + }); + } + assert_eq!(calls.load(Ordering::Relaxed), 1); + assert_eq!(payload_calls.load(Ordering::Relaxed), 1); +} + +#[test] +fn lazy_debug_observes_cached_state_with_a_non_send_initializer() { + let calls = std::cell::Cell::new(0); + let label: Rc = Rc::from("ready"); + let value = kv::ValueLazy::new(|| { + calls.set(calls.get() + 1); + label.to_string() + }); + assert_eq!(format!("{value:?}"), "ValueLazy { value: }"); + assert_eq!(calls.get(), 0); + assert_eq!(value.to_string(), "ready"); + assert_eq!(value.view().to_str(), Some("ready")); + assert_eq!( + format!("{value:?}"), + format!("ValueLazy {{ value: {:?} }}", *value) + ); + assert_eq!(calls.get(), 1); +} + #[test] fn lazy_serde_skips_rejected_records_and_memoizes_across_dispatches() { struct CountCalls(AtomicUsize); @@ -377,23 +459,6 @@ fn lazy_serde_skips_rejected_records_and_memoizes_across_dispatches() { } } - #[derive(Debug)] - struct RejectDrop; - - impl Filter for RejectDrop { - fn filter_level(&self, _: Level) -> FilterResult { - FilterResult::Neutral - } - - fn filter(&self, record: &Record, _: &dyn Diagnostic) -> FilterResult { - if record.payload().as_str() == Some("drop") { - FilterResult::Reject - } else { - FilterResult::Neutral - } - } - } - let sink = RecordingAppender::default(); let logger = logforth_core::builder() .dispatch(|d| { @@ -404,11 +469,11 @@ fn lazy_serde_skips_rejected_records_and_memoizes_across_dispatches() { .build(); let calls = CountCalls(AtomicUsize::new(0)); assert!(logger.enabled(Level::Info)); - logforth_core::info!(logger, ["payload" = ValueSerde::new(&calls)], "drop"); + logforth_core::info!(logger, ["payload" = kv::serde(&calls)], "drop"); assert!(sink.events().is_empty()); assert_eq!(calls.0.load(Ordering::Relaxed), 0); - logforth_core::warn!(logger, ["payload" = ValueSerde::new(&calls)], "keep"); + logforth_core::warn!(logger, ["payload" = kv::serde(&calls)], "keep"); let events = sink.events(); assert_eq!(events.len(), 2); for event in events {