Log via log crate

This commit is contained in:
Joscha 2022-06-23 13:24:20 +02:00
parent bbe1ab7bfd
commit 1e61f15e8d
5 changed files with 53 additions and 32 deletions

1
Cargo.lock generated
View file

@ -137,6 +137,7 @@ dependencies = [
"directories", "directories",
"edit", "edit",
"futures", "futures",
"log",
"parking_lot", "parking_lot",
"rand", "rand",
"rusqlite", "rusqlite",

View file

@ -11,6 +11,7 @@ crossterm = "0.23.2"
directories = "4.0.1" directories = "4.0.1"
edit = "0.1.4" edit = "0.1.4"
futures = "0.3.21" futures = "0.3.21"
log = "0.4.17"
parking_lot = "0.12.1" parking_lot = "0.12.1"
rand = "0.8.5" rand = "0.8.5"
rusqlite = { version = "0.27.0", features = ["chrono"] } rusqlite = { version = "0.27.0", features = ["chrono"] }

View file

@ -3,6 +3,7 @@ use std::vec;
use async_trait::async_trait; use async_trait::async_trait;
use chrono::{DateTime, Utc}; use chrono::{DateTime, Utc};
use log::{Level, Log};
use parking_lot::Mutex; use parking_lot::Mutex;
use crate::store::{Msg, MsgStore, Path, Tree}; use crate::store::{Msg, MsgStore, Path, Tree};
@ -11,7 +12,7 @@ use crate::store::{Msg, MsgStore, Path, Tree};
pub struct LogMsg { pub struct LogMsg {
id: usize, id: usize,
time: DateTime<Utc>, time: DateTime<Utc>,
topic: String, level: Level,
content: String, content: String,
} }
@ -31,7 +32,7 @@ impl Msg for LogMsg {
} }
fn nick(&self) -> String { fn nick(&self) -> String {
self.topic.clone() format!("{}", self.level)
} }
fn content(&self) -> String { fn content(&self) -> String {
@ -40,19 +41,17 @@ impl Msg for LogMsg {
} }
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct Log { pub struct Logger(Arc<Mutex<Vec<LogMsg>>>);
entries: Arc<Mutex<Vec<LogMsg>>>,
}
#[async_trait] #[async_trait]
impl MsgStore<LogMsg> for Log { impl MsgStore<LogMsg> for Logger {
async fn path(&self, id: &usize) -> Path<usize> { async fn path(&self, id: &usize) -> Path<usize> {
Path::new(vec![*id]) Path::new(vec![*id])
} }
async fn tree(&self, root: &usize) -> Tree<LogMsg> { async fn tree(&self, root: &usize) -> Tree<LogMsg> {
let msgs = self let msgs = self
.entries .0
.lock() .lock()
.get(*root) .get(*root)
.map(|msg| vec![msg.clone()]) .map(|msg| vec![msg.clone()])
@ -65,35 +64,50 @@ impl MsgStore<LogMsg> for Log {
} }
async fn next_tree(&self, tree: &usize) -> Option<usize> { async fn next_tree(&self, tree: &usize) -> Option<usize> {
let len = self.entries.lock().len(); let len = self.0.lock().len();
tree.checked_add(1).filter(|t| *t < len) tree.checked_add(1).filter(|t| *t < len)
} }
async fn first_tree(&self) -> Option<usize> { async fn first_tree(&self) -> Option<usize> {
let empty = self.entries.lock().is_empty(); let empty = self.0.lock().is_empty();
Some(0).filter(|_| !empty) Some(0).filter(|_| !empty)
} }
async fn last_tree(&self) -> Option<usize> { async fn last_tree(&self) -> Option<usize> {
self.entries.lock().len().checked_sub(1) self.0.lock().len().checked_sub(1)
} }
} }
impl Log { impl Log for Logger {
pub fn new() -> Self { fn enabled(&self, metadata: &log::Metadata) -> bool {
Self { true
entries: Arc::new(Mutex::new(Vec::new())),
}
} }
pub fn log<S1: ToString, S2: ToString>(&self, topic: S1, content: S2) { fn log(&self, record: &log::Record) {
let mut guard = self.entries.lock(); if !self.enabled(record.metadata()) {
return;
}
let mut guard = self.0.lock();
let msg = LogMsg { let msg = LogMsg {
id: guard.len(), id: guard.len(),
time: Utc::now(), time: Utc::now(),
topic: topic.to_string(), level: record.level(),
content: content.to_string(), content: format!("<{}> {}", record.target(), record.args()),
}; };
guard.push(msg); guard.push(msg);
} }
fn flush(&self) {}
}
impl Logger {
pub fn init(level: Level) -> &'static Self {
let logger = Box::leak(Box::new(Self(Arc::new(Mutex::new(Vec::new())))));
log::set_logger(logger).expect("logger already set");
log::set_max_level(level.to_level_filter());
logger
}
} }

View file

@ -2,18 +2,28 @@
mod chat; mod chat;
mod euph; mod euph;
mod log; mod logger;
mod replies; mod replies;
mod store; mod store;
mod ui; mod ui;
mod vault; mod vault;
use directories::ProjectDirs; use directories::ProjectDirs;
use log::info;
use toss::terminal::Terminal; use toss::terminal::Terminal;
use ui::Ui; use ui::Ui;
use crate::logger::Logger;
#[tokio::main] #[tokio::main]
async fn main() -> anyhow::Result<()> { async fn main() -> anyhow::Result<()> {
let logger = Logger::init(log::Level::Debug);
info!(
"Welcome to {} {}",
env!("CARGO_PKG_NAME"),
env!("CARGO_PKG_VERSION")
);
let dirs = ProjectDirs::from("de", "plugh", "cove").expect("unable to determine directories"); let dirs = ProjectDirs::from("de", "plugh", "cove").expect("unable to determine directories");
println!("Data dir: {}", dirs.data_dir().to_string_lossy()); println!("Data dir: {}", dirs.data_dir().to_string_lossy());
@ -21,7 +31,7 @@ async fn main() -> anyhow::Result<()> {
let mut terminal = Terminal::new()?; let mut terminal = Terminal::new()?;
// terminal.set_measuring(true); // terminal.set_measuring(true);
Ui::run(&mut terminal).await?; Ui::run(&mut terminal, logger.clone()).await?;
drop(terminal); // So the vault can print again drop(terminal); // So the vault can print again
vault.close().await; vault.close().await;

View file

@ -2,6 +2,7 @@ use std::sync::{Arc, Weak};
use std::time::Duration; use std::time::Duration;
use crossterm::event::{Event, KeyCode, KeyEvent, KeyModifiers, MouseEvent}; use crossterm::event::{Event, KeyCode, KeyEvent, KeyModifiers, MouseEvent};
use log::debug;
use parking_lot::FairMutex; use parking_lot::FairMutex;
use tokio::sync::mpsc::error::TryRecvError; use tokio::sync::mpsc::error::TryRecvError;
use tokio::sync::mpsc::{self, UnboundedReceiver, UnboundedSender}; use tokio::sync::mpsc::{self, UnboundedReceiver, UnboundedSender};
@ -10,7 +11,7 @@ use toss::frame::{Frame, Pos, Size};
use toss::terminal::Terminal; use toss::terminal::Terminal;
use crate::chat::Chat; use crate::chat::Chat;
use crate::log::{Log, LogMsg}; use crate::logger::{LogMsg, Logger};
use crate::store::dummy::{DummyMsg, DummyStore}; use crate::store::dummy::{DummyMsg, DummyStore};
#[derive(Debug)] #[derive(Debug)]
@ -31,20 +32,16 @@ enum Visible {
pub struct Ui { pub struct Ui {
event_tx: UnboundedSender<UiEvent>, event_tx: UnboundedSender<UiEvent>,
log: Log,
visible: Visible, visible: Visible,
chat: Chat<DummyMsg, DummyStore>, chat: Chat<DummyMsg, DummyStore>,
log_chat: Chat<LogMsg, Log>, log_chat: Chat<LogMsg, Logger>,
} }
impl Ui { impl Ui {
const POLL_DURATION: Duration = Duration::from_millis(100); const POLL_DURATION: Duration = Duration::from_millis(100);
pub async fn run(terminal: &mut Terminal) -> anyhow::Result<()> { pub async fn run(terminal: &mut Terminal, logger: Logger) -> anyhow::Result<()> {
let log = Log::new();
log.log("Hello", "world!");
let (event_tx, event_rx) = mpsc::unbounded_channel(); let (event_tx, event_rx) = mpsc::unbounded_channel();
let crossterm_lock = Arc::new(FairMutex::new(())); let crossterm_lock = Arc::new(FairMutex::new(()));
@ -54,7 +51,6 @@ impl Ui {
let crossterm_event_task = task::spawn_blocking(|| { let crossterm_event_task = task::spawn_blocking(|| {
Self::poll_crossterm_events(event_tx_clone, weak_crossterm_lock) Self::poll_crossterm_events(event_tx_clone, weak_crossterm_lock)
}); });
log.log("main", "Started input polling task");
// Prepare dummy message store and chat for testing // Prepare dummy message store and chat for testing
let store = DummyStore::new() let store = DummyStore::new()
@ -82,10 +78,9 @@ impl Ui {
// the rest of the UI is also shut down and the client stops. // the rest of the UI is also shut down and the client stops.
let mut ui = Self { let mut ui = Self {
event_tx, event_tx,
log: log.clone(),
visible: Visible::Log, visible: Visible::Log,
chat, chat,
log_chat: Chat::new(log), log_chat: Chat::new(logger),
}; };
let result = tokio::select! { let result = tokio::select! {
e = ui.run_main(terminal, event_rx, crossterm_lock) => e, e = ui.run_main(terminal, event_rx, crossterm_lock) => e,
@ -184,7 +179,7 @@ impl Ui {
} }
match event.code { match event.code {
KeyCode::Char('e') => self.log.log("EE E", "E ee e!"), KeyCode::Char('e') => debug!("{:#?}", event),
KeyCode::F(1) => self.visible = Visible::Main, KeyCode::F(1) => self.visible = Visible::Main,
KeyCode::F(2) => self.visible = Visible::Log, KeyCode::F(2) => self.visible = Visible::Log,
_ => {} _ => {}