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);
}

View file

@ -1,10 +0,0 @@
use std::str::FromStr;
use logging::{Level, error};
pub fn handle_log_level_change<F: FnOnce(Level)>(log_level: String, callback: F) {
match Level::from_str(log_level.as_str()) {
Ok(level) => callback(level),
Err(_) => error!("got unexpected log level from config"; "level" => log_level),
};
}

View file

@ -3,12 +3,12 @@ use logging::{logger, FutureExt};
use server::Server;
use tower_lsp::LspService;
mod configuration;
mod navigation;
#[tokio::main]
async fn main() {
let _guard = logging::set_level(logging::Level::Debug);
// start with debug log level, and then adjust once we get the configuration from the client.
logging::set_level(logging::Level::Debug);
let stdin = tokio::io::stdin();
let stdout = tokio::io::stdout();

View file

@ -14,7 +14,6 @@ pub(crate) struct Context {
impl Context {
pub fn default() -> Context {
let events_loop = EventLoopBuilder::new().with_any_thread(true).build();
// let events_loop = glutin::event_loop::EventLoop::<()>::new_any_thread();
let gl_window = glutin::ContextBuilder::new()
.build_headless(&*events_loop, glutin::dpi::PhysicalSize::new(1, 1))
.unwrap();

View file

@ -25,8 +25,8 @@ pub struct ContextFacade {
server_rx: Receiver<ServerMessage>,
}
impl ContextFacade {
pub fn default() -> Self {
impl Default for ContextFacade {
fn default() -> Self {
let (client_tx, client_rx) = mpsc::sync_channel::<ClientMessage>(1);
let (server_tx, server_rx) = mpsc::sync_channel::<ServerMessage>(1);
let (start_chan, start_chan_recv) = mpsc::sync_channel::<()>(1);

View file

@ -1,9 +1,10 @@
use std::{collections::HashMap, ffi::OsStr, marker::Sync, path::Path, sync::Arc};
use std::{collections::HashMap, ffi::OsStr, marker::Sync, path::Path, sync::Arc, str::FromStr};
use filesystem::NormalizedPathBuf;
use futures::future::join_all;
use logging::{error, info, logger, trace, warn, FutureExt};
use serde_json::Value;
use serde::Deserialize;
use serde_json::{Value, from_value};
use tokio::sync::Mutex;
@ -36,6 +37,7 @@ where
pub client: Arc<Mutex<Client>>,
workspaces: Arc<Mutex<TSTMap<Arc<Workspace<G>>>>>,
gl_factory: F,
_log_guard: logging::GlobalLoggerGuard
}
impl<G, F> Server<G, F>
@ -48,6 +50,7 @@ where
client: Arc::new(Mutex::new(client)),
workspaces: Default::default(),
gl_factory,
_log_guard: logging::init_logger()
}
}
}
@ -390,23 +393,22 @@ where
Ok(None)
}
async fn did_change_configuration(&self, _params: DidChangeConfigurationParams) {
/* logging::slog_with_trace_id(|| {
#[derive(Deserialize)]
struct Configuration {
#[serde(alias = "logLevel")]
log_level: String,
}
#[logging_macro::with_trace_id]
async fn did_change_configuration(&self, params: DidChangeConfigurationParams) {
#[derive(Deserialize)]
struct Configuration {
#[serde(alias = "logLevel")]
log_level: String,
}
let config: Configuration = from_value(params.settings.as_object().unwrap().get("mcglsl").unwrap().to_owned()).unwrap();
let config: Configuration = from_value(params.settings.as_object().unwrap().get("mcglsl").unwrap().to_owned()).unwrap();
info!("got updated configuration"; "config" => params.settings.as_object().unwrap().get("mcglsl").unwrap().to_string());
info!("got updated configuration"; "config" => params.settings.as_object().unwrap().get("mcglsl").unwrap().to_string());
configuration::handle_log_level_change(config.log_level, |level| {
self.log_guard = None; // set to None so Drop is invoked
self.log_guard = Some(logging::set_logger_with_level(level));
})
}); */
match logging::Level::from_str(config.log_level.as_str()) {
Ok(level) => logging::set_level(level),
Err(_) => error!("got unexpected log level from config"; "level" => &config.log_level),
}
}
}

View file

@ -7,7 +7,7 @@ pub struct SourceNum(usize);
impl Display for SourceNum {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(format!("{}", self.0).as_str())
f.write_str(self.0.to_string().as_str())
}
}