Skip to main content

vulcan_luaskills/runtime/
logging.rs

1use std::sync::{Arc, OnceLock, RwLock};
2
3/// Stable runtime log level emitted by the LuaSkills library.
4/// LuaSkills 库发出的稳定运行时日志级别。
5#[derive(Debug, Clone, Copy, PartialEq, Eq)]
6pub enum RuntimeLogLevel {
7    /// Informational runtime event.
8    /// 信息级运行时事件。
9    Info,
10    /// Warning runtime event.
11    /// 告警级运行时事件。
12    Warn,
13    /// Error runtime event.
14    /// 错误级运行时事件。
15    Error,
16}
17
18/// Structured runtime log event forwarded from the library to the host callback.
19/// 从库转发到宿主回调的结构化运行时日志事件。
20#[derive(Debug, Clone)]
21pub struct RuntimeLogEvent {
22    /// Stable runtime log level.
23    /// 稳定的运行时日志级别。
24    pub level: RuntimeLogLevel,
25    /// Human-readable log message emitted by the library.
26    /// 由库发出的可读日志消息。
27    pub message: String,
28}
29
30/// Host callback type that receives runtime log events.
31/// 接收运行时日志事件的宿主回调类型。
32pub type RuntimeLogCallback = Arc<dyn Fn(&RuntimeLogEvent) + Send + Sync + 'static>;
33
34/// Global host log callback shared by the runtime until per-host routing is introduced.
35/// 在引入更细粒度宿主路由前,由运行时共享使用的全局宿主日志回调。
36static RUNTIME_LOG_CALLBACK: OnceLock<RwLock<Option<RuntimeLogCallback>>> = OnceLock::new();
37
38/// Return the shared runtime log callback container.
39/// 返回共享运行时日志回调容器。
40fn runtime_log_callback() -> &'static RwLock<Option<RuntimeLogCallback>> {
41    RUNTIME_LOG_CALLBACK.get_or_init(|| RwLock::new(None))
42}
43
44/// Register or replace the host-side runtime log callback.
45/// 注册或替换宿主侧运行时日志回调。
46pub fn set_log_callback(callback: Option<RuntimeLogCallback>) {
47    if let Ok(mut guard) = runtime_log_callback().write() {
48        *guard = callback;
49    }
50}
51
52/// Emit one structured runtime log event to the current host callback if it exists.
53/// 若当前宿主回调存在,则向其发送一条结构化运行时日志事件。
54pub fn emit(level: RuntimeLogLevel, message: impl Into<String>) {
55    let event = RuntimeLogEvent {
56        level,
57        message: message.into(),
58    };
59    let callback = runtime_log_callback()
60        .read()
61        .ok()
62        .and_then(|guard| guard.as_ref().cloned());
63    if let Some(callback) = callback {
64        callback(&event);
65    }
66}
67
68/// Emit one informational runtime log event.
69/// 发送一条信息级运行时日志事件。
70pub fn info(message: impl Into<String>) {
71    emit(RuntimeLogLevel::Info, message);
72}
73
74/// Emit one warning runtime log event.
75/// 发送一条告警级运行时日志事件。
76pub fn warn(message: impl Into<String>) {
77    emit(RuntimeLogLevel::Warn, message);
78}
79
80/// Emit one error runtime log event.
81/// 发送一条错误级运行时日志事件。
82pub fn error(message: impl Into<String>) {
83    emit(RuntimeLogLevel::Error, message);
84}