reimplemented+simplified switchable server logging

don't know how well it interacts with `log` (or upcoming tracing), so this may be temporary and/or incomplete. But it works for my application code at the least (as opposed to library code)
This commit is contained in:
Noah Santschi-Cooney 2022-12-01 01:25:45 +00:00
parent e7221304da
commit a797d5b378
No known key found for this signature in database
GPG key ID: 3B22282472C8AE48
7 changed files with 54 additions and 44 deletions

View file

@ -1,6 +1,6 @@
use rand::{rngs, Rng};
use slog_term::{FullFormat, PlainSyncDecorator};
use std::{cell::RefCell, sync::Arc};
use std::cell::RefCell;
use std::io::Stderr;
@ -9,26 +9,41 @@ use slog::*;
use slog_atomic::*;
pub use logging_macro::*;
pub use slog_scope::{scope, logger, error, warn, info, trace, debug, GlobalLoggerGuard};
pub use slog::{slog_o, FnValue, Level, Value, Record, Key, Serializer, Result};
pub use slog::{slog_o, FnValue, Key, Level, Record, Result, Serializer, Value};
pub use slog_scope::{debug, error, info, logger, scope, trace, warn, GlobalLoggerGuard};
pub use slog_scope_futures::FutureExt;
type LoggerBase = Fuse<LevelFilter<Fuse<FullFormat<PlainSyncDecorator<Stderr>>>>>;
pub fn new_trace_id() -> String {
let rng = CURRENT_RNG.with(|rng| rng.borrow_mut().gen::<[u8; 4]>());
format!("{:04x}", u32::from_be_bytes(rng))
}
pub fn set_level(level: Level) -> GlobalLoggerGuard {
slog_stdlog::init_with_level(log::Level::Trace).err().or(None);
let drain = Arc::new(logger_base(level).fuse());
DRAIN_SWITCH.ctrl().set(drain.clone());
slog_scope::set_global_logger(Logger::root(drain, o!()))
pub fn init_logger() -> GlobalLoggerGuard {
slog_stdlog::init_with_level(log::Level::Debug).unwrap();
slog_scope::set_global_logger(Logger::root(&*DRAIN_SWITCH, o!()))
}
fn logger_base(level: Level) -> LevelFilter<Fuse<FullFormat<PlainSyncDecorator<Stderr>>>> {
pub fn set_level(level: Level) {
let drain = match level {
Level::Critical => &*ERROR_DRAIN,
Level::Error => &*ERROR_DRAIN,
Level::Warning => &*WARN_DRAIN,
Level::Info => &*INFO_DRAIN,
Level::Debug => &*DEBUG_DRAIN,
Level::Trace => &*TRACE_DRAIN,
};
DRAIN_SWITCH.ctrl().set(drain);
eprintln!("new level {}", level);
}
fn logger_base(level: Level) -> LoggerBase {
let plain = slog_term::PlainSyncDecorator::new(std::io::stderr());
let drain = slog_term::FullFormat::new(plain).build().fuse();
drain.filter_level(level)
drain.filter_level(level).fuse()
}
thread_local! {
@ -37,7 +52,11 @@ thread_local! {
lazy_static! {
static ref DRAIN_SWITCH: AtomicSwitch<()> = {
let logger = logger_base(Level::Info).fuse();
AtomicSwitch::new(logger)
AtomicSwitch::new(&*DEBUG_DRAIN)
};
static ref TRACE_DRAIN: LoggerBase = logger_base(Level::Trace);
static ref DEBUG_DRAIN: LoggerBase = logger_base(Level::Debug);
static ref INFO_DRAIN: LoggerBase = logger_base(Level::Info);
static ref WARN_DRAIN: LoggerBase = logger_base(Level::Warning);
static ref ERROR_DRAIN: LoggerBase = logger_base(Level::Error);
}