transcribe_cpp/logging.rs
1//! Routing the native log sink into the [`log`] crate facade.
2//!
3//! Call [`init_logging`] once at process startup (before loading any model) to
4//! send every library and ggml diagnostic through `log` (and thus to whatever
5//! `env_logger`/`tracing-log`/etc. the application installed). This matches the
6//! C contract: `transcribe_log_set` is a once-at-startup global.
7
8use std::ffi::CStr;
9
10use transcribe_cpp_sys as sys;
11
12/// The C log callback: map the level and forward the message to `log`.
13///
14/// A panic must not unwind into C (that aborts the process), and the installed
15/// logger can panic, e.g. fern when stdout and stderr are both closed pipes. A
16/// failed log line is dropped instead.
17extern "C" fn log_trampoline(
18 level: sys::transcribe_log_level,
19 msg: *const std::os::raw::c_char,
20 _userdata: *mut std::os::raw::c_void,
21) {
22 let _ = std::panic::catch_unwind(|| forward_log(level, msg));
23}
24
25fn forward_log(level: sys::transcribe_log_level, msg: *const std::os::raw::c_char) {
26 if msg.is_null() {
27 return;
28 }
29 // SAFETY: `msg` is a NUL-terminated string valid for this call.
30 let text = unsafe { CStr::from_ptr(msg) }.to_string_lossy();
31 let text = text.trim_end_matches('\n');
32 use sys::transcribe_log_level as L;
33 let level = match level {
34 L::TRANSCRIBE_LOG_LEVEL_ERROR => log::Level::Error,
35 L::TRANSCRIBE_LOG_LEVEL_WARN => log::Level::Warn,
36 L::TRANSCRIBE_LOG_LEVEL_DEBUG => log::Level::Debug,
37 // INFO and CONT (continuation fragments) both surface at info.
38 L::TRANSCRIBE_LOG_LEVEL_INFO | L::TRANSCRIBE_LOG_LEVEL_CONT => log::Level::Info,
39 // NONE or any unknown level: drop.
40 _ => return,
41 };
42 log::log!(target: "transcribe_cpp", level, "{text}");
43}
44
45/// Route native + ggml diagnostics into the [`log`] crate. Call once at
46/// startup, before loading models.
47pub fn init_logging() {
48 // SAFETY: install-once-at-startup is the supported usage model.
49 unsafe { sys::transcribe_log_set(Some(log_trampoline), std::ptr::null_mut()) };
50}
51
52/// Silence the native library entirely (drops both library and ggml messages,
53/// including the stderr default). Call once at startup.
54pub fn disable_logging() {
55 unsafe { sys::transcribe_log_set(None, std::ptr::null_mut()) };
56}