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
157// `debug`/`warning` are part of the internal log API; exercised by tests and
158// kept for parity with the Go SDK's tdLogDebug/tdLogWarning helpers. The
159// `info`/`error` helpers are wired into the (feature-gated) consumers, and
160// `error` is additionally exercised by this module's own tests.
161#[cfg(any(feature = "blocking", feature = "async"))]
162pub(crate) fn td_log_info(message: &str) {
163    td_log(TDLogLevel::Info, message);
164}
165
166#[allow(dead_code)]
167pub(crate) fn td_log_warning(message: &str) {
168    td_log(TDLogLevel::Warning, message);
169}
170
171#[cfg(any(feature = "blocking", feature = "async", test))]
172pub(crate) fn td_log_error(message: &str) {
173    td_log(TDLogLevel::Error, message);
174}
175
176#[cfg(test)]
177mod tests {
178    use super::*;
179    use std::sync::Mutex;
180    use std::sync::atomic::AtomicUsize;
181
182    // The global log level and custom logger are process-wide; serialize every
183    // test that touches them so parallel execution cannot interfere.
184    static LOG_TEST_LOCK: Mutex<()> = Mutex::new(());
185
186    struct CountingLogger {
187        lines: Mutex<Vec<String>>,
188        panics: bool,
189        calls: AtomicUsize,
190    }
191
192    impl CountingLogger {
193        fn new(panics: bool) -> Arc<Self> {
194            Arc::new(Self {
195                lines: Mutex::new(Vec::new()),
196                panics,
197                calls: AtomicUsize::new(0),
198            })
199        }
200    }
201
202    impl TDLogger for CountingLogger {
203        fn print(&self, message: &str) {
204            self.calls.fetch_add(1, Ordering::SeqCst);
205            if self.panics {
206                panic!("logger panic");
207            }
208            self.lines.lock().unwrap().push(message.to_string());
209        }
210    }
211
212    struct Guard;
213
214    impl Drop for Guard {
215        fn drop(&mut self) {
216            clear_custom_logger();
217            set_log_level(TDLogLevel::Off);
218        }
219    }
220
221    #[test]
222    fn respects_level_threshold() {
223        let _guard = Guard;
224        let _serial = LOG_TEST_LOCK.lock().unwrap();
225        let logger = CountingLogger::new(false);
226        set_custom_logger(logger.clone());
227        set_log_level(TDLogLevel::Warning);
228
229        td_log_debug("hidden");
230        td_log_warning("shown");
231
232        let lines = logger.lines.lock().unwrap();
233        assert_eq!(lines.len(), 1);
234        assert!(lines[0].contains("[Warning] shown"));
235    }
236
237    #[test]
238    fn contains_panic_from_custom_logger() {
239        let _guard = Guard;
240        let _serial = LOG_TEST_LOCK.lock().unwrap();
241        let logger = CountingLogger::new(true);
242        set_custom_logger(logger.clone());
243        set_log_level(TDLogLevel::Error);
244        td_log_error("boom");
245        assert_eq!(logger.calls.load(Ordering::SeqCst), 1);
246    }
247
248    #[test]
249    fn default_level_is_off() {
250        let _serial = LOG_TEST_LOCK.lock().unwrap();
251        assert_eq!(get_log_level(), TDLogLevel::Off);
252    }
253}