Skip to main content

thinkingdata_core/
log.rs

1// Copyright 2026 houseme
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
15//! SDK diagnostics logging.
16//!
17//! Logging is disabled by default ([`TDLogLevel::Off`]). Raise the level with
18//! [`set_log_level`], or route diagnostics into your own logging stack by
19//! installing a [`TDLogger`] implementation with [`set_custom_logger`]:
20//!
21//! ```
22//! use std::sync::{Arc, Mutex};
23//! use thinkingdata_core::log::{set_custom_logger, set_log_level, TDLogger, TDLogLevel};
24//!
25//! struct Collect(Mutex<Vec<String>>);
26//! impl TDLogger for Collect {
27//!     fn print(&self, message: &str) {
28//!         self.0.lock().unwrap().push(message.to_string());
29//!     }
30//! }
31//!
32//! set_custom_logger(Arc::new(Collect(Mutex::new(Vec::new()))));
33//! set_log_level(TDLogLevel::Info);
34//! assert_eq!(thinkingdata_core::log::get_log_level(), TDLogLevel::Info);
35//! set_log_level(TDLogLevel::Off);
36//! ```
37
38use std::sync::{Arc, Mutex, atomic::AtomicU8, atomic::Ordering};
39
40/// Prefix prepended to every diagnostic message.
41pub const SDK_LOG_PREFIX: &str = "[ThinkingData]";
42
43/// The log output level, ordered from quietest to most verbose.
44#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
45#[repr(u8)]
46pub enum TDLogLevel {
47    /// Disable all logging (default).
48    Off = 1,
49    /// Errors only.
50    Error = 2,
51    /// Errors and warnings.
52    Warning = 3,
53    /// Errors, warnings and informational messages.
54    Info = 4,
55    /// Everything, including per-event payloads.
56    Debug = 5,
57}
58
59impl TDLogLevel {
60    fn as_u8(self) -> u8 {
61        self as u8
62    }
63
64    fn from_u8(value: u8) -> TDLogLevel {
65        match value {
66            2 => TDLogLevel::Error,
67            3 => TDLogLevel::Warning,
68            4 => TDLogLevel::Info,
69            5 => TDLogLevel::Debug,
70            _ => TDLogLevel::Off,
71        }
72    }
73
74    fn tag(self) -> &'static str {
75        match self {
76            TDLogLevel::Error => "[Error] ",
77            TDLogLevel::Warning => "[Warning] ",
78            TDLogLevel::Info => "[Info] ",
79            TDLogLevel::Debug | TDLogLevel::Off => "[Info] ",
80        }
81    }
82}
83
84/// A destination for SDK diagnostic messages.
85///
86/// `print` may be called concurrently from multiple threads. Panics inside a
87/// custom logger are contained so logging can never interrupt event delivery.
88pub trait TDLogger: Send + Sync {
89    /// Receive one formatted diagnostic line (trailing newline included).
90    fn print(&self, message: &str);
91}
92
93static LOG_LEVEL: AtomicU8 = AtomicU8::new(1); // TDLogLevel::Off
94static CUSTOM_LOGGER: Mutex<Option<Arc<dyn TDLogger>>> = Mutex::new(None);
95
96/// Set the log output level.
97///
98/// The default is [`TDLogLevel::Off`]. Note that constructing a
99/// [`DebugConsumer`](crate::consumer::DebugConsumer) raises the global level
100/// to [`TDLogLevel::Debug`], matching the official Go SDK behavior.
101pub fn set_log_level(level: TDLogLevel) {
102    LOG_LEVEL.store(level.as_u8(), Ordering::SeqCst);
103}
104
105/// Get the current log output level.
106pub fn get_log_level() -> TDLogLevel {
107    TDLogLevel::from_u8(LOG_LEVEL.load(Ordering::SeqCst))
108}
109
110/// Install a custom logger that receives every formatted diagnostic message.
111///
112/// Pass an [`Arc`] wrapping your implementation; call [`clear_custom_logger`]
113/// to remove it again.
114pub fn set_custom_logger(logger: Arc<dyn TDLogger>) {
115    let mut guard = CUSTOM_LOGGER.lock().expect("ThinkingData logger poisoned");
116    *guard = Some(logger);
117}
118
119/// Remove a previously installed custom logger.
120pub fn clear_custom_logger() {
121    let mut guard = CUSTOM_LOGGER.lock().expect("ThinkingData logger poisoned");
122    *guard = None;
123}
124
125/// Emit one diagnostic message if `level` is enabled.
126///
127/// The custom logger is invoked outside of any lock, mirroring the Go SDK's
128/// rule that user code never runs while SDK configuration locks are held.
129pub(crate) fn td_log(level: TDLogLevel, message: &str) {
130    if level > get_log_level() || level == TDLogLevel::Off {
131        return;
132    }
133    let line = format!("{SDK_LOG_PREFIX}{}{message}\n", level.tag());
134    let logger = {
135        let guard = CUSTOM_LOGGER.lock().expect("ThinkingData logger poisoned");
136        guard.clone()
137    };
138    if let Some(logger) = logger {
139        let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
140            logger.print(&line);
141        }));
142        let _ = result;
143    } else {
144        // Default destination: stdout, timestamped like the Go SDK.
145        let now = crate::utils::format_now();
146        print!("[{now}]{line}");
147    }
148}
149
150// `debug`/`warning` are part of the internal log API; exercised by tests and
151// kept for parity with the Go SDK's tdLogDebug/tdLogWarning helpers.
152#[allow(dead_code)]
153pub(crate) fn td_log_debug(message: &str) {
154    td_log(TDLogLevel::Debug, message);
155}
156
157pub(crate) fn td_log_info(message: &str) {
158    td_log(TDLogLevel::Info, message);
159}
160
161#[allow(dead_code)]
162pub(crate) fn td_log_warning(message: &str) {
163    td_log(TDLogLevel::Warning, message);
164}
165
166pub(crate) fn td_log_error(message: &str) {
167    td_log(TDLogLevel::Error, message);
168}
169
170#[cfg(test)]
171mod tests {
172    use super::*;
173    use std::sync::Mutex;
174    use std::sync::atomic::AtomicUsize;
175
176    // The global log level and custom logger are process-wide; serialize every
177    // test that touches them so parallel execution cannot interfere.
178    static LOG_TEST_LOCK: Mutex<()> = Mutex::new(());
179
180    struct CountingLogger {
181        lines: Mutex<Vec<String>>,
182        panics: bool,
183        calls: AtomicUsize,
184    }
185
186    impl CountingLogger {
187        fn new(panics: bool) -> Arc<Self> {
188            Arc::new(Self {
189                lines: Mutex::new(Vec::new()),
190                panics,
191                calls: AtomicUsize::new(0),
192            })
193        }
194    }
195
196    impl TDLogger for CountingLogger {
197        fn print(&self, message: &str) {
198            self.calls.fetch_add(1, Ordering::SeqCst);
199            if self.panics {
200                panic!("logger panic");
201            }
202            self.lines.lock().unwrap().push(message.to_string());
203        }
204    }
205
206    struct Guard;
207
208    impl Drop for Guard {
209        fn drop(&mut self) {
210            clear_custom_logger();
211            set_log_level(TDLogLevel::Off);
212        }
213    }
214
215    #[test]
216    fn respects_level_threshold() {
217        let _guard = Guard;
218        let _serial = LOG_TEST_LOCK.lock().unwrap();
219        let logger = CountingLogger::new(false);
220        set_custom_logger(logger.clone());
221        set_log_level(TDLogLevel::Warning);
222
223        td_log_debug("hidden");
224        td_log_warning("shown");
225
226        let lines = logger.lines.lock().unwrap();
227        assert_eq!(lines.len(), 1);
228        assert!(lines[0].contains("[Warning] shown"));
229    }
230
231    #[test]
232    fn contains_panic_from_custom_logger() {
233        let _guard = Guard;
234        let _serial = LOG_TEST_LOCK.lock().unwrap();
235        let logger = CountingLogger::new(true);
236        set_custom_logger(logger.clone());
237        set_log_level(TDLogLevel::Error);
238        td_log_error("boom");
239        assert_eq!(logger.calls.load(Ordering::SeqCst), 1);
240    }
241
242    #[test]
243    fn default_level_is_off() {
244        let _serial = LOG_TEST_LOCK.lock().unwrap();
245        assert_eq!(get_log_level(), TDLogLevel::Off);
246    }
247}