logforth_core/diagnostic/
thread_local.rs

1// Copyright 2024 FastLabs Developers
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use std::cell::RefCell;
16use std::collections::BTreeMap;
17
18use crate::Diagnostic;
19use crate::Error;
20use crate::kv::Visitor;
21
22thread_local! {
23    static CONTEXT: RefCell<BTreeMap<String, String>> = const { RefCell::new(BTreeMap::new()) };
24}
25
26/// A diagnostic that stores key-value pairs in a thread-local map.
27///
28/// ## Example
29///
30/// ```
31/// use logforth_core::diagnostic::ThreadLocalDiagnostic;
32///
33/// ThreadLocalDiagnostic::insert("key", "value");
34/// ```
35#[derive(Default, Debug, Clone, Copy)]
36#[non_exhaustive]
37pub struct ThreadLocalDiagnostic {}
38
39impl ThreadLocalDiagnostic {
40    /// Inserts a key-value pair into the thread local diagnostic .
41    pub fn insert<K, V>(key: K, value: V)
42    where
43        K: Into<String>,
44        V: Into<String>,
45    {
46        CONTEXT.with(|map| {
47            map.borrow_mut().insert(key.into(), value.into());
48        });
49    }
50
51    /// Removes a key-value pair from the thread local diagnostic.
52    pub fn remove(key: &str) {
53        CONTEXT.with(|map| {
54            map.borrow_mut().remove(key);
55        });
56    }
57}
58
59impl Diagnostic for ThreadLocalDiagnostic {
60    fn visit(&self, visitor: &mut dyn Visitor) -> Result<(), Error> {
61        CONTEXT.with(|map| {
62            let map = map.borrow();
63            for (key, value) in map.iter() {
64                visitor.visit(key.as_str().into(), value.as_str().into())?;
65            }
66            Ok(())
67        })
68    }
69}