From 8d6b256b1c7b3eadf7cab1cec97b832b0a85cd94 Mon Sep 17 00:00:00 2001 From: Alexandre Bury Date: Sat, 18 May 2019 08:38:24 -0700 Subject: [PATCH] More public fields in cursive::logger --- src/logger.rs | 48 ++++++++++++++++++++++++++++++++++++------------ 1 file changed, 36 insertions(+), 12 deletions(-) diff --git a/src/logger.rs b/src/logger.rs index 6e04813..5823836 100644 --- a/src/logger.rs +++ b/src/logger.rs @@ -7,7 +7,7 @@ use std::sync::Mutex; /// Saves all log records in a global deque. /// /// Uses a `DebugView` to access it. -struct CursiveLogger; +pub struct CursiveLogger; static LOGGER: CursiveLogger = CursiveLogger; @@ -27,22 +27,27 @@ lazy_static! { Mutex::new(VecDeque::new()); } +/// 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(), + }); +} + impl log::Log for CursiveLogger { fn enabled(&self, _metadata: &log::Metadata<'_>) -> bool { true } fn log(&self, 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(), - }); + log(record); } fn flush(&self) {} @@ -56,7 +61,7 @@ impl log::Log for CursiveLogger { /// [`Cursive::toggle_debug_console()`](crate::Cursive::toggle_debug_console()). pub fn init() { // TODO: Configure the deque size? - LOGS.lock().unwrap().reserve(1_000); + reserve_logs(1_000); // This will panic if `set_logger` was already called. log::set_logger(&LOGGER).unwrap(); @@ -64,3 +69,22 @@ pub fn init() { // TODO: read the level from env variable? From argument? log::set_max_level(log::LevelFilter::Trace); } + +/// 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); +}