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::Key;
21use crate::kv::Value;
22use crate::kv::Visitor;
23
24thread_local! {
25 static CONTEXT: RefCell<BTreeMap<String, String>> = const { RefCell::new(BTreeMap::new()) };
26}
27
28/// A diagnostic that stores key-value pairs in a thread-local map.
29///
30/// ## Example
31///
32/// ```
33/// use logforth_core::diagnostic::ThreadLocalDiagnostic;
34///
35/// ThreadLocalDiagnostic::insert("key", "value");
36/// ```
37#[derive(Default, Debug, Clone, Copy)]
38#[non_exhaustive]
39pub struct ThreadLocalDiagnostic {}
40
41impl ThreadLocalDiagnostic {
42 /// Insert a key-value pair into the thread local diagnostic .
43 pub fn insert<K, V>(key: K, value: V)
44 where
45 K: Into<String>,
46 V: Into<String>,
47 {
48 CONTEXT.with(|map| {
49 map.borrow_mut().insert(key.into(), value.into());
50 });
51 }
52
53 /// Remove a key-value pair from the thread local diagnostic.
54 pub fn remove(key: &str) {
55 CONTEXT.with(|map| {
56 map.borrow_mut().remove(key);
57 });
58 }
59}
60
61impl Diagnostic for ThreadLocalDiagnostic {
62 fn visit(&self, visitor: &mut dyn Visitor) -> Result<(), Error> {
63 CONTEXT.with(|map| {
64 let map = map.borrow();
65 for (key, value) in map.iter() {
66 let key = Key::new_ref(key.as_str());
67 let value = Value::from(value);
68 visitor.visit(key, value)?;
69 }
70 Ok(())
71 })
72 }
73}