Skip to main content

context_logger/
context.rs

1//! Context builder for structured logging.
2
3use std::borrow::Cow;
4
5use crate::{LogValue, stack::ScopeFrame};
6
7/// A set of records that can be attached to a logging scope.
8///
9/// [`LogContext`] represents a set of key-value pairs that will be
10/// automatically added to log messages when the context scope is active.
11#[derive(Debug, Clone)]
12pub struct LogContext {
13    pub(crate) frame: ScopeFrame,
14}
15
16impl LogContext {
17    /// Creates a new, empty context.
18    #[must_use]
19    pub const fn new() -> Self {
20        Self {
21            frame: ScopeFrame::new(),
22        }
23    }
24
25    /// Adds a record to this context.
26    ///
27    /// # Ordering
28    ///
29    /// The order in which records appear in log output is **not guaranteed**.
30    /// Do not rely on any specific ordering of keys.
31    ///
32    /// # Examples
33    ///
34    /// ```
35    /// use context_logger::LogContext;
36    ///
37    /// let context = LogContext::new()
38    ///     .with_record("user_id", "user-123")
39    ///     .with_record("request_id", 42)
40    ///     .with_record("is_admin", true);
41    /// ```
42    #[must_use]
43    pub fn with_record(
44        mut self,
45        key: impl Into<Cow<'static, str>>,
46        value: impl Into<LogValue>,
47    ) -> Self {
48        let record = (key, value);
49        self.frame.push(record);
50        self
51    }
52}
53
54impl Default for LogContext {
55    fn default() -> Self {
56        Self::new()
57    }
58}