feat: lua logger improvements

distinct fn for setup and get, setup is idempotent
This commit is contained in:
əlemi 2024-08-06 23:02:28 +02:00
parent cd9a2d6247
commit 2cc23f2ec2
Signed by: alemi
GPG key ID: A4895B84D311642C

View file

@ -1,14 +1,18 @@
use std::io::Write; use std::io::Write;
use std::sync::{mpsc, Arc, Mutex}; use std::sync::atomic::AtomicBool;
use std::sync::Mutex;
use crate::api::Cursor; use crate::api::Cursor;
use crate::prelude::*; use crate::prelude::*;
use mlua::prelude::*; use mlua::prelude::*;
use tokio::runtime::Runtime; use tokio::runtime::Runtime;
use tokio::sync::broadcast;
lazy_static::lazy_static!{ lazy_static::lazy_static!{
// TODO use a runtime::Builder::new_current_thread() runtime to not behave like malware // TODO use a runtime::Builder::new_current_thread() runtime to not behave like malware
static ref STATE : GlobalState = GlobalState::default(); static ref STATE : GlobalState = GlobalState::default();
static ref LOG : broadcast::Sender<String> = broadcast::channel(32).0;
static ref ONCE : AtomicBool = AtomicBool::new(false);
} }
struct GlobalState { struct GlobalState {
@ -199,36 +203,29 @@ impl LuaUserData for CodempTextChange {
// setup library logging to file // setup library logging to file
#[derive(Debug, derive_more::From)] #[derive(Debug, derive_more::From)]
struct LuaLogger(Arc<Mutex<mpsc::Receiver<String>>>); struct LuaLogger(broadcast::Receiver<String>);
impl LuaUserData for LuaLogger { impl LuaUserData for LuaLogger {
fn add_methods<'lua, M: LuaUserDataMethods<'lua, Self>>(methods: &mut M) { fn add_methods<'lua, M: LuaUserDataMethods<'lua, Self>>(methods: &mut M) {
methods.add_method("recv", |_, this, ()| { methods.add_method_mut("recv", |_, this, ()| {
Ok( Ok(this.0.blocking_recv().expect("logger channel closed"))
this.0
.lock()
.expect("logger mutex poisoned")
.recv()
.expect("logger channel closed")
)
}); });
} }
} }
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
struct LuaLoggerProducer(mpsc::Sender<String>); struct LuaLoggerProducer;
impl Write for LuaLoggerProducer { impl Write for LuaLoggerProducer {
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> { fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
self.0.send(String::from_utf8_lossy(buf).to_string()) let _ = LOG.send(String::from_utf8_lossy(buf).to_string());
.expect("could not write on logger channel");
Ok(buf.len()) Ok(buf.len())
} }
fn flush(&mut self) -> std::io::Result<()> { Ok(()) } fn flush(&mut self) -> std::io::Result<()> { Ok(()) }
} }
fn setup_tracing(_: &Lua, (debug,): (Option<bool>,)) -> LuaResult<LuaLogger> { fn setup_logger(_: &Lua, (debug, path): (Option<bool>, Option<String>)) -> LuaResult<()> {
let (tx, rx) = mpsc::channel(); if ONCE.load(std::sync::atomic::Ordering::Relaxed) { return Ok(()) }
let level = if debug.unwrap_or(false) { tracing::Level::DEBUG } else {tracing::Level::INFO };
let format = tracing_subscriber::fmt::format() let format = tracing_subscriber::fmt::format()
.with_level(true) .with_level(true)
.with_target(true) .with_target(true)
@ -239,12 +236,27 @@ fn setup_tracing(_: &Lua, (debug,): (Option<bool>,)) -> LuaResult<LuaLogger> {
.with_line_number(false) .with_line_number(false)
.with_source_location(false) .with_source_location(false)
.compact(); .compact();
tracing_subscriber::fmt()
let level = if debug.unwrap_or_default() { tracing::Level::DEBUG } else {tracing::Level::INFO };
let builder = tracing_subscriber::fmt()
.event_format(format) .event_format(format)
.with_max_level(level) .with_max_level(level);
.with_writer(Mutex::new(LuaLoggerProducer(tx)))
.init(); if let Some(path) = path {
Ok(LuaLogger(Arc::new(Mutex::new(rx)))) let logfile = std::fs::File::create(path).expect("failed creating logfile");
builder.with_writer(Mutex::new(logfile)).init();
} else {
builder.with_writer(Mutex::new(LuaLoggerProducer)).init();
}
ONCE.store(true, std::sync::atomic::Ordering::Relaxed);
Ok(())
}
fn get_logger(_: &Lua, (): ()) -> LuaResult<LuaLogger> {
let sub = LOG.subscribe();
Ok(LuaLogger(sub))
} }
// define module and exports // define module and exports
@ -259,9 +271,9 @@ fn codemp_lua(lua: &Lua) -> LuaResult<LuaTable> {
exports.set("get_workspace", lua.create_function(get_workspace)?)?; exports.set("get_workspace", lua.create_function(get_workspace)?)?;
// debug // debug
exports.set("id", lua.create_function(id)?)?; exports.set("id", lua.create_function(id)?)?;
exports.set("setup_tracing", lua.create_function(setup_tracing)?)?; exports.set("get_logger", lua.create_function(get_logger)?)?;
exports.set("setup_logger", lua.create_function(setup_logger)?)?;
Ok(exports) Ok(exports)
} }