Skip to main content

oa/runtime/
log.rs

1//! Engine-owned structured host logging.
2
3use std::{
4	cell::RefCell,
5	fmt,
6	fs::{self, File, OpenOptions},
7	io::{self, Write},
8	path::{Path, PathBuf},
9	sync::{
10		Arc, Mutex, Weak,
11		atomic::{AtomicU8, Ordering},
12	},
13};
14
15use chrono::Local;
16
17use crate::{Error, Result};
18
19/// Severity threshold and record level for OA diagnostics.
20#[repr(u8)]
21#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
22pub enum LogLevel {
23	/// Fine-grained diagnostics; macro call sites compile out in release builds.
24	Trace,
25	/// Developer-facing state; macro call sites compile out in release builds.
26	Debug,
27	/// Meaningful lifecycle or capability state.
28	Info,
29	/// A recoverable degradation or fallback.
30	Warn,
31	/// A failed action that the caller still handles explicitly.
32	Error,
33	/// An unrecoverable condition at the current owner; this does not terminate.
34	Fatal,
35	/// Disable every record.
36	Off,
37}
38
39impl LogLevel {
40	const fn label(self) -> &'static str {
41		match self {
42			Self::Trace => "TRACE",
43			Self::Debug => "DEBUG",
44			Self::Info => "INFO ",
45			Self::Warn => "WARN ",
46			Self::Error => "ERROR",
47			Self::Fatal => "FATAL",
48			Self::Off => "OFF  ",
49		}
50	}
51
52	const fn color(self) -> &'static str {
53		match self {
54			Self::Trace => "\x1b[90m",
55			Self::Debug => "\x1b[36m",
56			Self::Info => "\x1b[32m",
57			Self::Warn => "\x1b[33m",
58			Self::Error => "\x1b[31m",
59			Self::Fatal => "\x1b[35m",
60			Self::Off => "",
61		}
62	}
63}
64
65/// Compact one-to-four-character diagnostic component tag.
66#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
67pub struct LogComponent {
68	bytes: [u8; 4],
69	len: u8,
70}
71
72impl LogComponent {
73	/// Foundation values and backend-neutral contracts.
74	pub const CORE: Self = Self::constant(*b"CORE", 4);
75	/// Device, memory, queue, stream, and descriptor machinery.
76	pub const RUNTIME: Self = Self::constant(*b"RT  ", 2);
77	/// Engine ownership and lifecycle.
78	pub const ENGINE: Self = Self::constant(*b"ENGN", 4);
79	/// Graphs, kernels, dispatch, and GEMM.
80	pub const COMPUTE: Self = Self::constant(*b"COMP", 4);
81	/// Machine-learning operations and sessions.
82	pub const ML: Self = Self::constant(*b"ML  ", 2);
83	/// Dataset and serialization operations.
84	pub const DATA: Self = Self::constant(*b"DATA", 4);
85	/// Vision operations.
86	pub const VISION: Self = Self::constant(*b"VISN", 4);
87	/// Video operations and sessions.
88	pub const VIDEO: Self = Self::constant(*b"VID ", 3);
89	/// Audio operations and sessions.
90	pub const AUDIO: Self = Self::constant(*b"AUD ", 3);
91	/// Rendering operations and sessions.
92	pub const RENDER: Self = Self::constant(*b"RNDR", 4);
93	/// User-interface operations.
94	pub const UI: Self = Self::constant(*b"UI  ", 2);
95	/// Plotting operations.
96	pub const PLOT: Self = Self::constant(*b"PLOT", 4);
97	/// Animation operations.
98	pub const ANIMATION: Self = Self::constant(*b"ANIM", 4);
99	/// Network operations and sessions.
100	pub const NETWORK: Self = Self::constant(*b"NET ", 3);
101	/// Cryptographic operations.
102	pub const CRYPTOGRAPHY: Self = Self::constant(*b"CRYP", 4);
103	/// Python binding diagnostics.
104	pub const PYTHON: Self = Self::constant(*b"PY  ", 2);
105	/// Application and SDK diagnostics.
106	pub const APP: Self = Self::constant(*b"APP ", 3);
107	/// Model Context Protocol operations.
108	pub const MCP: Self = Self::constant(*b"MCP ", 3);
109
110	const fn constant(bytes: [u8; 4], len: u8) -> Self {
111		Self { bytes, len }
112	}
113
114	/// Construct a custom ASCII component tag.
115	///
116	/// # Errors
117	///
118	/// Returns an error unless `tag` contains one through four printable ASCII
119	/// characters.
120	pub fn new(tag: &str) -> Result<Self> {
121		let source = tag.as_bytes();
122		if source.is_empty() || source.len() > 4 || !source.iter().all(u8::is_ascii_graphic) {
123			return Err(Error::invalid_argument(
124				"log component tags require one through four printable ASCII characters",
125			));
126		}
127		let mut bytes = [b' '; 4];
128		bytes[..source.len()].copy_from_slice(source);
129		let len = u8::try_from(source.len())
130			.map_err(|_| Error::invalid_argument("log component tag length exceeds its storage width"))?;
131		Ok(Self { bytes, len })
132	}
133
134	/// Return this component's unpadded tag.
135	pub fn tag(self) -> String {
136		self.bytes[..usize::from(self.len)]
137			.iter()
138			.map(|byte| char::from(*byte))
139			.collect()
140	}
141}
142
143impl fmt::Display for LogComponent {
144	fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
145		for byte in self.bytes {
146			fmt::Write::write_char(formatter, char::from(byte))?;
147		}
148		Ok(())
149	}
150}
151
152/// Configuration for the logging session owned by an [`Engine`](super::Engine).
153#[derive(Clone, Debug)]
154#[must_use]
155pub struct LogOptions {
156	directory: Option<PathBuf>,
157	prefix: String,
158	minimum_level: LogLevel,
159	console_output: bool,
160	file_output: bool,
161	color_output: bool,
162}
163
164impl Default for LogOptions {
165	fn default() -> Self {
166		Self {
167			directory: None,
168			prefix: "oa".to_owned(),
169			minimum_level: if cfg!(debug_assertions) {
170				LogLevel::Debug
171			} else {
172				LogLevel::Info
173			},
174			console_output: true,
175			file_output: false,
176			color_output: true,
177		}
178	}
179}
180
181impl LogOptions {
182	/// Create default console logging options.
183	pub fn new() -> Self {
184		Self::default()
185	}
186
187	/// Select the directory used when file output is enabled.
188	pub fn directory(mut self, directory: impl Into<PathBuf>) -> Self {
189		self.directory = Some(directory.into());
190		self
191	}
192
193	/// Select the safe filename prefix used when file output is enabled.
194	pub fn prefix(mut self, prefix: impl Into<String>) -> Self {
195		self.prefix = prefix.into();
196		self
197	}
198
199	/// Set the minimum emitted severity.
200	pub const fn minimum_level(mut self, minimum_level: LogLevel) -> Self {
201		self.minimum_level = minimum_level;
202		self
203	}
204
205	/// Enable or disable synchronous standard-error output.
206	pub const fn console_output(mut self, enabled: bool) -> Self {
207		self.console_output = enabled;
208		self
209	}
210
211	/// Enable or disable append-only dated file output.
212	pub const fn file_output(mut self, enabled: bool) -> Self {
213		self.file_output = enabled;
214		self
215	}
216
217	/// Enable or disable ANSI severity colors on console output.
218	pub const fn color_output(mut self, enabled: bool) -> Self {
219		self.color_output = enabled;
220		self
221	}
222
223	/// Return the configured minimum severity.
224	pub const fn level(&self) -> LogLevel {
225		self.minimum_level
226	}
227}
228
229struct StoredIoError {
230	kind: io::ErrorKind,
231	message: String,
232}
233
234impl StoredIoError {
235	fn new(error: &io::Error) -> Self {
236		Self {
237			kind: error.kind(),
238			message: error.to_string(),
239		}
240	}
241
242	fn to_error(&self) -> Error {
243		Error::io(
244			"logging output",
245			io::Error::new(self.kind, self.message.clone()),
246		)
247	}
248}
249
250struct LogState {
251	file: Option<File>,
252	path: Option<PathBuf>,
253	console_output: bool,
254	color_output: bool,
255	open: bool,
256	first_error: Option<StoredIoError>,
257}
258
259struct LogInner {
260	minimum_level: AtomicU8,
261	state: Mutex<LogState>,
262}
263
264#[derive(Clone)]
265pub(crate) struct Logger {
266	inner: Arc<LogInner>,
267}
268
269impl Logger {
270	pub(crate) fn new(options: LogOptions) -> Result<Self> {
271		if options.prefix.is_empty()
272			|| !options
273				.prefix
274				.bytes()
275				.all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_'))
276		{
277			return Err(Error::invalid_argument(
278				"log filename prefix requires ASCII letters, digits, '-' or '_'",
279			));
280		}
281
282		let (file, path) = if options.file_output {
283			let directory = options
284				.directory
285				.as_deref()
286				.ok_or_else(|| Error::invalid_argument("log file output requires a directory"))?;
287			fs::create_dir_all(directory)
288				.map_err(|source| Error::io("log directory creation", source))?;
289			let path = log_path(directory, &options.prefix);
290			let file = OpenOptions::new()
291				.create(true)
292				.append(true)
293				.open(&path)
294				.map_err(|source| Error::io("log file opening", source))?;
295			(Some(file), Some(path))
296		} else {
297			(None, None)
298		};
299
300		Ok(Self {
301			inner: Arc::new(LogInner {
302				minimum_level: AtomicU8::new(options.minimum_level as u8),
303				state: Mutex::new(LogState {
304					file,
305					path,
306					console_output: options.console_output,
307					color_output: options.color_output,
308					open: true,
309					first_error: None,
310				}),
311			}),
312		})
313	}
314
315	pub(crate) fn select(&self) -> LogSelection {
316		let selected = Arc::downgrade(&self.inner);
317		let previous = CURRENT_LOG
318			.try_with(|current| {
319				current
320					.try_borrow_mut()
321					.map(|mut current| std::mem::replace(&mut *current, selected.clone()))
322					.ok()
323			})
324			.ok()
325			.flatten()
326			.unwrap_or_default();
327		LogSelection { selected, previous }
328	}
329
330	pub(crate) fn write_text(
331		&self,
332		level: LogLevel,
333		component: LogComponent,
334		text: &str,
335	) -> Result<()> {
336		self.inner.write_text(level, component, text)
337	}
338
339	pub(crate) fn set_level(&self, level: LogLevel) {
340		self
341			.inner
342			.minimum_level
343			.store(level as u8, Ordering::Relaxed);
344	}
345
346	pub(crate) fn level(&self) -> LogLevel {
347		level_from_u8(self.inner.minimum_level.load(Ordering::Relaxed))
348	}
349
350	pub(crate) fn path(&self) -> Option<PathBuf> {
351		self.inner.lock_state().path.clone()
352	}
353
354	pub(crate) fn flush(&self) -> Result<()> {
355		self.inner.flush()
356	}
357
358	pub(crate) fn close(&self) -> Result<()> {
359		self.inner.close()
360	}
361}
362
363impl LogInner {
364	fn lock_state(&self) -> std::sync::MutexGuard<'_, LogState> {
365		match self.state.lock() {
366			Ok(state) => state,
367			Err(poisoned) => poisoned.into_inner(),
368		}
369	}
370
371	fn should_write(&self, level: LogLevel) -> bool {
372		level != LogLevel::Off && (level as u8) >= self.minimum_level.load(Ordering::Relaxed)
373	}
374
375	fn write_text(&self, level: LogLevel, component: LogComponent, text: &str) -> Result<()> {
376		if !self.should_write(level) {
377			return Ok(());
378		}
379		let timestamp = Local::now().format("%H:%M:%S%.3f");
380		let record = format!("{timestamp} [{}] [{component}] {text}\n", level.label());
381		let mut state = self.lock_state();
382		if !state.open {
383			return Err(Error::failed_precondition("logger is closed"));
384		}
385
386		if let Some(file) = &mut state.file
387			&& let Err(error) = file.write_all(record.as_bytes())
388		{
389			state
390				.first_error
391				.get_or_insert_with(|| StoredIoError::new(&error));
392		}
393		if state.console_output {
394			let result = if state.color_output {
395				write!(io::stderr().lock(), "{}{}\x1b[0m", level.color(), record)
396			} else {
397				io::stderr().lock().write_all(record.as_bytes())
398			};
399			if let Err(error) = result {
400				state
401					.first_error
402					.get_or_insert_with(|| StoredIoError::new(&error));
403			}
404		}
405		match &state.first_error {
406			Some(error) => Err(error.to_error()),
407			None => Ok(()),
408		}
409	}
410
411	fn flush(&self) -> Result<()> {
412		let mut state = self.lock_state();
413		if let Some(file) = &mut state.file
414			&& let Err(error) = file.flush()
415		{
416			state
417				.first_error
418				.get_or_insert_with(|| StoredIoError::new(&error));
419		}
420		match &state.first_error {
421			Some(error) => Err(error.to_error()),
422			None => Ok(()),
423		}
424	}
425
426	fn close(&self) -> Result<()> {
427		let mut state = self.lock_state();
428		if !state.open {
429			return match &state.first_error {
430				Some(error) => Err(error.to_error()),
431				None => Ok(()),
432			};
433		}
434		if let Some(mut file) = state.file.take()
435			&& let Err(error) = file.flush()
436		{
437			state
438				.first_error
439				.get_or_insert_with(|| StoredIoError::new(&error));
440		}
441		state.open = false;
442		match &state.first_error {
443			Some(error) => Err(error.to_error()),
444			None => Ok(()),
445		}
446	}
447}
448
449fn log_path(directory: &Path, prefix: &str) -> PathBuf {
450	directory.join(format!("{prefix}_{}.log", Local::now().format("%Y%m%d")))
451}
452
453fn level_from_u8(value: u8) -> LogLevel {
454	match value {
455		0 => LogLevel::Trace,
456		1 => LogLevel::Debug,
457		2 => LogLevel::Info,
458		3 => LogLevel::Warn,
459		4 => LogLevel::Error,
460		5 => LogLevel::Fatal,
461		_ => LogLevel::Off,
462	}
463}
464
465thread_local! {
466	static CURRENT_LOG: RefCell<Weak<LogInner>> = const { RefCell::new(Weak::new()) };
467}
468
469#[derive(Clone)]
470pub(crate) struct LogSelection {
471	selected: Weak<LogInner>,
472	previous: Weak<LogInner>,
473}
474
475impl LogSelection {
476	/// A selection marker that shares this selection's identity but performs no
477	/// restore on drop. Used by `Engine` clones: only the instance that
478	/// installed the selection owns restoring the prior logger, or a temporary
479	/// clone's drop would deselect the live logger mid-process.
480	pub(crate) fn detached(&self) -> Self {
481		Self {
482			selected: Weak::new(),
483			previous: Weak::new(),
484		}
485	}
486}
487
488impl Drop for LogSelection {
489	fn drop(&mut self) {
490		let _ = CURRENT_LOG.try_with(|current| {
491			let Ok(mut current) = current.try_borrow_mut() else {
492				return;
493			};
494			if Weak::ptr_eq(&current, &self.selected) {
495				*current = self.previous.clone();
496			}
497		});
498	}
499}
500
501fn selected() -> Option<Arc<LogInner>> {
502	CURRENT_LOG
503		.try_with(|current| {
504			current
505				.try_borrow()
506				.ok()
507				.and_then(|current| current.upgrade())
508		})
509		.ok()
510		.flatten()
511}
512
513#[doc(hidden)]
514pub fn __log_should_write(level: LogLevel) -> bool {
515	level != LogLevel::Off && selected().is_none_or(|logger| logger.should_write(level))
516}
517
518#[doc(hidden)]
519pub fn __log_write(level: LogLevel, component: LogComponent, arguments: fmt::Arguments<'_>) {
520	let text = arguments.to_string();
521	if let Some(logger) = selected() {
522		let _ = logger.write_text(level, component, &text);
523	} else {
524		let timestamp = Local::now().format("%H:%M:%S%.3f");
525		let record = format!(
526			"{}{} [{}] [{component}] {text}\x1b[0m\n",
527			level.color(),
528			timestamp,
529			level.label()
530		);
531		let _ = io::stderr().lock().write_all(record.as_bytes());
532	}
533}
534
535#[macro_export]
536/// Write an informational record through the selected engine logger.
537macro_rules! log_info {
538	($component:expr, $($argument:tt)*) => {{
539		if $crate::runtime::__log_should_write($crate::LogLevel::Info) {
540			$crate::runtime::__log_write(
541				$crate::LogLevel::Info,
542				$component,
543				format_args!($($argument)*),
544			);
545		}
546	}};
547}
548
549#[macro_export]
550/// Write a recoverable-warning record through the selected engine logger.
551macro_rules! log_warn {
552	($component:expr, $($argument:tt)*) => {{
553		if $crate::runtime::__log_should_write($crate::LogLevel::Warn) {
554			$crate::runtime::__log_write(
555				$crate::LogLevel::Warn,
556				$component,
557				format_args!($($argument)*),
558			);
559		}
560	}};
561}
562
563#[macro_export]
564/// Write an error record without changing control flow.
565macro_rules! log_error {
566	($component:expr, $($argument:tt)*) => {{
567		if $crate::runtime::__log_should_write($crate::LogLevel::Error) {
568			$crate::runtime::__log_write(
569				$crate::LogLevel::Error,
570				$component,
571				format_args!($($argument)*),
572			);
573		}
574	}};
575}
576
577#[macro_export]
578/// Write a fatal-severity record without terminating execution.
579macro_rules! log_fatal {
580	($component:expr, $($argument:tt)*) => {{
581		if $crate::runtime::__log_should_write($crate::LogLevel::Fatal) {
582			$crate::runtime::__log_write(
583				$crate::LogLevel::Fatal,
584				$component,
585				format_args!($($argument)*),
586			);
587		}
588	}};
589}
590
591#[cfg(debug_assertions)]
592#[macro_export]
593/// Write a trace record in debug builds; release builds do not evaluate arguments.
594macro_rules! log_trace {
595	($component:expr, $($argument:tt)*) => {{
596		if $crate::runtime::__log_should_write($crate::LogLevel::Trace) {
597			$crate::runtime::__log_write(
598				$crate::LogLevel::Trace,
599				$component,
600				format_args!($($argument)*),
601			);
602		}
603	}};
604}
605
606#[cfg(not(debug_assertions))]
607#[macro_export]
608/// Compile out a trace record without evaluating its arguments.
609macro_rules! log_trace {
610	($component:expr, $($argument:tt)*) => {{}};
611}
612
613#[cfg(debug_assertions)]
614#[macro_export]
615/// Write a debug record in debug builds; release builds do not evaluate arguments.
616macro_rules! log_debug {
617	($component:expr, $($argument:tt)*) => {{
618		if $crate::runtime::__log_should_write($crate::LogLevel::Debug) {
619			$crate::runtime::__log_write(
620				$crate::LogLevel::Debug,
621				$component,
622				format_args!($($argument)*),
623			);
624		}
625	}};
626}
627
628#[cfg(not(debug_assertions))]
629#[macro_export]
630/// Compile out a debug record without evaluating its arguments.
631macro_rules! log_debug {
632	($component:expr, $($argument:tt)*) => {{}};
633}