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::atomic::AtomicUsize;
180    use std::sync::{Mutex, MutexGuard, PoisonError};
181
182    // The global log level and custom logger are process-wide; serialize every
183    // test that touches them so parallel execution cannot interfere. Tests of
184    // other modules still emit `td_log_error` lines on their own (e.g. via
185    // `extract_string_property`) while one of these tests has raised the
186    // level, so assertions tolerate interleaved entries, and the lock is
187    // taken poison-tolerantly: a failing sibling must not cascade into
188    // PoisonError failures here.
189    static LOG_TEST_LOCK: Mutex<()> = Mutex::new(());
190
191    fn serial_lock() -> MutexGuard<'static, ()> {
192        LOG_TEST_LOCK.lock().unwrap_or_else(PoisonError::into_inner)
193    }
194
195    struct CountingLogger {
196        lines: Mutex<Vec<String>>,
197        panics: bool,
198        calls: AtomicUsize,
199    }
200
201    impl CountingLogger {
202        fn new(panics: bool) -> Arc<Self> {
203            Arc::new(Self {
204                lines: Mutex::new(Vec::new()),
205                panics,
206                calls: AtomicUsize::new(0),
207            })
208        }
209    }
210
211    impl TDLogger for CountingLogger {
212        fn print(&self, message: &str) {
213            self.calls.fetch_add(1, Ordering::SeqCst);
214            if self.panics {
215                panic!("logger panic");
216            }
217            self.lines.lock().unwrap().push(message.to_string());
218        }
219    }
220
221    // Declared after the serial lock so the reverse drop order restores the
222    // global state *before* releasing the lock.
223    struct Guard;
224
225    impl Drop for Guard {
226        fn drop(&mut self) {
227            clear_custom_logger();
228            set_log_level(TDLogLevel::Off);
229        }
230    }
231
232    #[test]
233    fn respects_level_threshold() {
234        let _serial = serial_lock();
235        let _guard = Guard;
236        let logger = CountingLogger::new(false);
237        set_custom_logger(logger.clone());
238        set_log_level(TDLogLevel::Warning);
239
240        td_log_debug("hidden");
241        td_log_warning("shown");
242
243        let lines = logger.lines.lock().unwrap();
244        // The threshold semantics: the debug line is filtered, the warning
245        // line is delivered. Interleaved error-level lines from concurrent
246        // tests may also appear, so the exact length is not asserted.
247        assert!(
248            !lines.iter().any(|line| line.contains("hidden")),
249            "{lines:?}"
250        );
251        assert!(
252            lines.iter().any(|line| line.contains("[Warning] shown")),
253            "{lines:?}"
254        );
255    }
256
257    #[test]
258    fn contains_panic_from_custom_logger() {
259        let _serial = serial_lock();
260        let _guard = Guard;
261        let logger = CountingLogger::new(true);
262        set_custom_logger(logger.clone());
263        set_log_level(TDLogLevel::Error);
264        td_log_error("boom");
265        // Reaching this line proves containment: the panic raised in `print`
266        // was swallowed by `td_log`. The exact call count is racy —
267        // concurrent tests may legitimately emit error-level lines through
268        // the same global logger — so only "at least our own call" holds.
269        assert!(logger.calls.load(Ordering::SeqCst) >= 1);
270    }
271
272    #[test]
273    fn default_level_is_off() {
274        let _serial = serial_lock();
275        assert_eq!(get_log_level(), TDLogLevel::Off);
276    }
277}