quantum_log 0.3.0

High-performance asynchronous logging framework based on tracing ecosystem
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
//! QuantumLog - 高性能异步日志库
//!
//! QuantumLog 是一个专为高性能计算环境设计的异步日志库,
//! 支持多种输出格式和目标,包括文件、数据库和标准输出。
//!
//! # 快速开始
//!
//! ```rust
//! use quantum_log::{init, shutdown};
//! use tracing::{info, warn, error};
//!
//! #[tokio::main]
//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
//!     // 初始化 QuantumLog
//!     init().await?;
//!     
//!     // 使用标准的 tracing 宏
//!     info!("Application started");
//!     warn!("This is a warning");
//!     error!("This is an error");
//!     
//!     // 优雅关闭
//!     shutdown().await?;
//!     Ok(())
//! }
//! ```
//!
//! # 自定义配置
//!
//! ```rust
//! use quantum_log::{QuantumLogConfig, init_with_config};
//!
//! #[tokio::main]
//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
//!     let config = QuantumLogConfig {
//!         global_level: "DEBUG".to_string(),
//!         ..Default::default()
//!     };
//!     
//!     quantum_log::init_with_config(config).await?;
//!     
//!     // 你的应用代码...
//!     
//!     quantum_log::shutdown().await?;
//!     Ok(())
//! }
//! ```

pub mod config;
pub mod core;
pub mod diagnostics;
pub mod error;
pub mod mpi;
pub mod shutdown;
pub mod sinks;
pub mod utils;

#[cfg(feature = "database")]
pub mod database {
    pub use crate::sinks::database::*;
}

pub use config::{
    load_config_from_file, BackpressureStrategy, OutputFormat, QuantumLogConfig,
    QuantumLoggerConfig, StdoutConfig,
};
pub use diagnostics::{get_diagnostics, DiagnosticsSnapshot};
pub use error::{QuantumLogError, Result};
pub use shutdown::{
    ShutdownCoordinator, ShutdownHandle as QuantumShutdownHandle, ShutdownListener, ShutdownSignal,
    ShutdownState,
};

pub use core::event::QuantumLogEvent;
pub use core::subscriber::{BufferStats, QuantumLogSubscriber, QuantumLogSubscriberBuilder};

use once_cell::sync::Lazy;
use std::sync::{
    atomic::{AtomicBool, Ordering},
    Arc, Mutex,
};
// Initialize diagnostics
use crate::diagnostics::init_diagnostics;

/// 库版本
pub const VERSION: &str = env!("CARGO_PKG_VERSION");

/// 全局订阅器实例
static GLOBAL_SUBSCRIBER: Lazy<Arc<Mutex<Option<QuantumLogSubscriber>>>> =
    Lazy::new(|| Arc::new(Mutex::new(None)));

/// QuantumLog 初始化标记
/// 用于确保日志系统只被初始化一次
pub static IS_QUANTUM_LOG_INITIALIZED: AtomicBool = AtomicBool::new(false);

/// 使用默认配置初始化 QuantumLog
///
/// 这是一个便捷函数,使用默认配置初始化 QuantumLog。
/// 默认配置包括:
/// - 启用控制台输出
/// - 日志级别为 INFO
/// - 使用默认格式化器
///
/// # 示例
///
/// ```rust
/// use quantum_log::init;
///
/// #[tokio::main]
/// async fn main() -> Result<(), Box<dyn std::error::Error>> {
///     init().await?;
///     tracing::info!("Hello, QuantumLog!");
///     Ok(())
/// }
/// ```
pub async fn init() -> Result<()> {
    // Ensure diagnostics subsystem is initialized early
    let _ = init_diagnostics();

    let config = QuantumLogConfig {
        pre_init_stdout_enabled: true,
        stdout: Some(crate::config::StdoutConfig {
            enabled: true,
            ..Default::default()
        }),
        ..Default::default()
    };

    let mut subscriber = QuantumLogSubscriber::with_config(config)?;

    // 初始化订阅器
    subscriber.initialize().await?;

    // 存储订阅器实例以便后续关闭
    if let Ok(mut global) = GLOBAL_SUBSCRIBER.lock() {
        *global = Some(subscriber.clone());
    }

    // 安装为全局订阅器
    subscriber.install_global()?;

    Ok(())
}

/// 使用指定配置初始化 QuantumLog
///
/// # 参数
///
/// * `config` - QuantumLog 配置
///
/// # 示例
///
/// ```rust
/// use quantum_log::{QuantumLogConfig, init_with_config};
///
/// #[tokio::main]
/// async fn main() -> Result<(), Box<dyn std::error::Error>> {
///     let config = QuantumLogConfig {
///         global_level: "DEBUG".to_string(),
///         ..Default::default()
///     };
///     
///     quantum_log::init_with_config(config).await?;
///     quantum_log::shutdown().await?;
///     Ok(())
/// }
/// ```
pub async fn init_with_config(config: QuantumLogConfig) -> Result<()> {
    // Ensure diagnostics subsystem is initialized early
    let _ = init_diagnostics();

    let mut subscriber = QuantumLogSubscriber::with_config(config)?;

    // 初始化订阅器
    subscriber.initialize().await?;

    // 存储订阅器实例以便后续关闭
    if let Ok(mut global) = GLOBAL_SUBSCRIBER.lock() {
        *global = Some(subscriber.clone());
    }

    // 安装为全局订阅器(这会消费 subscriber)
    subscriber.install_global()?;

    Ok(())
}

/// 使用构建器初始化 QuantumLog
///
/// # 参数
///
/// * `builder_fn` - 构建器配置函数
///
/// # 示例
///
/// ```rust
/// use quantum_log::{init_with_builder, shutdown};
///
/// #[tokio::main]
/// async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
///     init_with_builder(|builder| {
///         builder
///             .max_buffer_size(5000)
///             .custom_field("service", "my-app")
///             .custom_field("version", "1.0.0")
///     }).await?;
///     
///     shutdown().await?;
///     Ok(())
/// }
/// ```
pub async fn init_with_builder<F>(
    builder_fn: F,
) -> std::result::Result<(), Box<dyn std::error::Error + Send + Sync>>
where
    F: FnOnce(QuantumLogSubscriberBuilder) -> QuantumLogSubscriberBuilder,
{
    // Ensure diagnostics subsystem is initialized early
    let _ = init_diagnostics();

    let builder = QuantumLogSubscriber::builder();
    let mut subscriber = builder_fn(builder).build()?;

    // 初始化订阅器
    subscriber.initialize().await?;

    // 存储订阅器实例以便后续关闭
    if let Ok(mut global) = GLOBAL_SUBSCRIBER.lock() {
        *global = Some(subscriber.clone());
    }

    // 安装为全局订阅器(这会消费 subscriber)
    subscriber.install_global()?;

    Ok(())
}

/// 优雅关闭 QuantumLog
///
/// 这会关闭所有 sink 并等待它们完成处理所有待处理的事件。
/// 建议在应用程序退出前调用此函数。
///
/// # 示例
///
/// ```rust
/// use quantum_log::{init, shutdown};
///
/// #[tokio::main]
/// async fn main() -> Result<(), Box<dyn std::error::Error>> {
///     init().await?;
///     
///     // 你的应用代码...
///     
///     shutdown().await?;
///     Ok(())
/// }
/// ```
pub async fn shutdown() -> Result<()> {
    let subscriber = if let Ok(mut global) = GLOBAL_SUBSCRIBER.lock() {
        global.take()
    } else {
        None
    };

    if let Some(subscriber) = subscriber {
        subscriber.shutdown().await?;
    }
    Ok(())
}

/// 获取缓冲区统计信息
///
/// 返回当前预初始化缓冲区的统计信息,包括当前大小、丢弃的事件数量等。
///
/// # 示例
///
/// ```rust
/// use quantum_log::{init, get_buffer_stats, shutdown};
///
/// #[tokio::main]
/// async fn main() -> Result<(), Box<dyn std::error::Error>> {
///     init().await?;
///     
///     let stats = get_buffer_stats();
///     if let Some(stats) = stats {
///         println!("Buffer size: {}, Dropped: {}", stats.current_size, stats.dropped_count);
///     }
///     
///     shutdown().await?;
///     Ok(())
/// }
/// ```
pub fn get_buffer_stats() -> Option<BufferStats> {
    if let Ok(global) = GLOBAL_SUBSCRIBER.lock() {
        global
            .as_ref()
            .map(|subscriber| subscriber.get_buffer_stats())
    } else {
        None
    }
}

/// 检查 QuantumLog 是否已初始化
///
/// # 示例
///
/// ```rust
/// use quantum_log::{init, is_initialized, shutdown};
///
/// #[tokio::main]
/// async fn main() -> Result<(), Box<dyn std::error::Error>> {
///     assert!(!is_initialized());
///     
///     init().await?;
///     assert!(is_initialized());
///     
///     shutdown().await?;
///     Ok(())
/// }
/// ```
pub fn is_initialized() -> bool {
    if let Ok(global) = GLOBAL_SUBSCRIBER.lock() {
        global
            .as_ref()
            .is_some_and(|subscriber| subscriber.is_initialized())
    } else {
        false
    }
}

/// 获取当前配置的引用
///
/// 返回当前 QuantumLog 实例使用的配置。如果 QuantumLog 未初始化,返回 None。
pub fn get_config() -> Option<QuantumLogConfig> {
    if let Ok(global) = GLOBAL_SUBSCRIBER.lock() {
        global
            .as_ref()
            .map(|subscriber| subscriber.config().clone())
    } else {
        None
    }
}

// 外部依赖
use tokio::sync::oneshot;

/// 关闭句柄,用于优雅关闭日志系统
#[derive(Debug)]
pub struct ShutdownHandle {
    sender: Option<oneshot::Sender<()>>,
}

impl ShutdownHandle {
    /// 创建新的关闭句柄
    pub fn new(sender: oneshot::Sender<()>) -> Self {
        Self {
            sender: Some(sender),
        }
    }

    /// 触发优雅关闭
    pub async fn shutdown(mut self) -> Result<()> {
        if let Some(sender) = self.sender.take() {
            sender.send(()).map_err(|_| {
                QuantumLogError::ShutdownError("Failed to send shutdown signal".to_string())
            })?;
        }
        Ok(())
    }
}

/// 初始化 QuantumLog 日志系统
///
/// 这是设计文档中指定的主要初始化函数,它会:
/// 1. 检查是否已经初始化,确保只初始化一次
/// 2. 使用默认配置创建并初始化 QuantumLogSubscriber
/// 3. 返回 ShutdownHandle 用于优雅关闭
///
/// # 返回值
///
/// 返回 `ShutdownHandle`,可用于优雅关闭日志系统
///
/// # 错误
///
/// 如果日志系统已经初始化,将返回错误
///
/// # 示例
///
/// ```rust
/// use quantum_log::init_quantum_logger;
///
/// #[tokio::main]
/// async fn main() -> Result<(), Box<dyn std::error::Error>> {
///     let shutdown_handle = init_quantum_logger().await?;
///     
///     // 你的应用代码...
///     
///     shutdown_handle.shutdown().await?;
///     Ok(())
/// }
/// ```
pub async fn init_quantum_logger() -> Result<ShutdownHandle> {
    // Ensure diagnostics subsystem is initialized early
    let _ = init_diagnostics();

    // 检查是否已经初始化
    if IS_QUANTUM_LOG_INITIALIZED
        .compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst)
        .is_err()
    {
        return Err(QuantumLogError::InitializationError(
            "QuantumLog has already been initialized".to_string(),
        ));
    }

    // 创建默认配置的订阅器
    let mut subscriber = QuantumLogSubscriber::new().map_err(|e| {
        QuantumLogError::InitializationError(format!("Failed to create subscriber: {}", e))
    })?;

    // 初始化订阅器
    subscriber.initialize().await.map_err(|e| {
        QuantumLogError::InitializationError(format!("Failed to initialize subscriber: {}", e))
    })?;

    // 创建关闭通道
    let (shutdown_sender, shutdown_receiver) = oneshot::channel();

    // 克隆订阅器用于关闭任务
    let subscriber_for_shutdown = subscriber.clone();

    // 保存订阅器到全局状态
    if let Ok(mut global) = GLOBAL_SUBSCRIBER.lock() {
        *global = Some(subscriber.clone());
    } else {
        // 如果获取锁失败,重置初始化标记
        IS_QUANTUM_LOG_INITIALIZED.store(false, Ordering::SeqCst);
        return Err(QuantumLogError::InitializationError(
            "Failed to acquire global subscriber lock".to_string(),
        ));
    }

    // 安装为全局订阅器
    if let Err(e) = subscriber.install_global() {
        // 如果安装失败,清理状态
        IS_QUANTUM_LOG_INITIALIZED.store(false, Ordering::SeqCst);
        if let Ok(mut global) = GLOBAL_SUBSCRIBER.lock() {
            *global = None;
        }
        return Err(QuantumLogError::InitializationError(format!(
            "Failed to install global subscriber: {}",
            e
        )));
    }

    // 启动关闭监听任务
    tokio::spawn(async move {
        if shutdown_receiver.await.is_ok() {
            // 执行优雅关闭
            if let Err(e) = subscriber_for_shutdown.shutdown().await {
                eprintln!("Error during shutdown: {}", e);
            }
            // 重置初始化标记
            IS_QUANTUM_LOG_INITIALIZED.store(false, Ordering::SeqCst);
            // 清理全局订阅器
            if let Ok(mut global) = GLOBAL_SUBSCRIBER.lock() {
                *global = None;
            }
        }
    });

    Ok(ShutdownHandle::new(shutdown_sender))
}