cursive/cursive-core/src/logger.rs

91 lines
2.3 KiB
Rust
Raw Normal View History

2019-02-22 20:38:16 +00:00
//! Logging utilities
2019-03-01 00:04:14 +00:00
use lazy_static::lazy_static;
2019-02-22 20:38:16 +00:00
use std::collections::VecDeque;
use std::sync::Mutex;
/// Saves all log records in a global deque.
///
/// Uses a `DebugView` to access it.
2019-05-18 15:38:24 +00:00
pub struct CursiveLogger;
2019-02-22 20:38:16 +00:00
static LOGGER: CursiveLogger = CursiveLogger;
2019-02-22 21:55:07 +00:00
/// A log record.
pub struct Record {
/// Log level used for this record
pub level: log::Level,
/// Time this message was logged
pub time: chrono::DateTime<chrono::Utc>,
/// Message content
pub message: String,
}
2019-02-22 20:38:16 +00:00
lazy_static! {
/// Circular buffer for logs. Use it to implement `DebugView`.
2019-02-22 21:55:07 +00:00
pub static ref LOGS: Mutex<VecDeque<Record>> =
2019-02-22 20:38:16 +00:00
Mutex::new(VecDeque::new());
}
2019-05-18 15:38:24 +00:00
/// Log a record in cursive's log queue.
pub fn log(record: &log::Record<'_>) {
let mut logs = LOGS.lock().unwrap();
// TODO: customize the format? Use colors? Save more info?
if logs.len() == logs.capacity() {
logs.pop_front();
}
logs.push_back(Record {
level: record.level(),
message: format!("{}", record.args()),
time: chrono::Utc::now(),
});
}
2019-02-22 20:38:16 +00:00
impl log::Log for CursiveLogger {
2019-02-28 23:55:02 +00:00
fn enabled(&self, _metadata: &log::Metadata<'_>) -> bool {
2019-02-22 20:38:16 +00:00
true
}
2019-02-28 23:55:02 +00:00
fn log(&self, record: &log::Record<'_>) {
2019-05-18 15:38:24 +00:00
log(record);
2019-02-22 20:38:16 +00:00
}
fn flush(&self) {}
}
/// Initialize the Cursive logger.
///
/// Make sure this is the only logger your are using.
///
/// Use a [`DebugView`](crate::views::DebugView) to see the logs, or use
/// [`Cursive::toggle_debug_console()`](crate::Cursive::toggle_debug_console()).
2019-02-22 20:38:16 +00:00
pub fn init() {
// TODO: Configure the deque size?
2019-05-18 15:38:24 +00:00
reserve_logs(1_000);
2019-02-22 20:38:16 +00:00
// This will panic if `set_logger` was already called.
log::set_logger(&LOGGER).unwrap();
// TODO: read the level from env variable? From argument?
log::set_max_level(log::LevelFilter::Trace);
}
2019-05-18 15:38:24 +00:00
/// Return a logger that stores records in cursive's log queue.
///
/// These logs can then be read by a [`DebugView`](crate::views::DebugView).
///
/// An easier alternative might be to use [`init()`].
pub fn get_logger() -> CursiveLogger {
reserve_logs(1_000);
CursiveLogger
}
/// Adds `n` more entries to cursive's log queue.
///
/// Most of the time you don't need to use this directly.
///
/// You should call this if you're not using `init()` nor `get_logger()`.
pub fn reserve_logs(n: usize) {
LOGS.lock().unwrap().reserve(n);
}