feat: send logs into admin room

Log entries will automatically be deduplicated, so a message won't be
sent if the same line has already been sent in the last 30 mins
This commit is contained in:
Timo Kösters 2020-11-14 23:13:06 +01:00
parent ecea0d4af2
commit 9439f2c183
No known key found for this signature in database
GPG key ID: 24DA7517711A2BA4
6 changed files with 87 additions and 23 deletions

View file

@ -1,7 +1,14 @@
use std::{time::Duration, collections::HashMap, sync::RwLock, time::Instant};
use log::error;
use ruma::api::client::{error::ErrorKind, r0::uiaa::UiaaInfo};
use ruma::{
api::client::{error::ErrorKind, r0::uiaa::UiaaInfo},
events::room::message,
};
use thiserror::Error;
use crate::{database::admin::AdminCommand, Database};
#[cfg(feature = "conduit_bin")]
use {
crate::RumaResponse,
@ -53,6 +60,11 @@ impl Error {
error!("BadDatabase: {}", message);
Self::BadDatabase(message)
}
pub fn bad_config(message: &'static str) -> Self {
error!("BadConfig: {}", message);
Self::BadConfig(message)
}
}
#[cfg(feature = "conduit_bin")]
@ -95,3 +107,50 @@ where
.respond_to(r)
}
}
pub struct ConduitLogger {
pub db: Database,
pub last_logs: RwLock<HashMap<String, Instant>>,
}
impl log::Log for ConduitLogger {
fn enabled(&self, _metadata: &log::Metadata<'_>) -> bool {
true
}
fn log(&self, record: &log::Record<'_>) {
let output = format!("{} - {}", record.level(), record.args());
println!("{}", output);
if self.enabled(record.metadata())
&& record
.module_path()
.map_or(false, |path| path.starts_with("conduit::"))
{
if self
.last_logs
.read()
.unwrap()
.get(&output)
.map_or(false, |i| i.elapsed() < Duration::from_secs(60 * 30))
{
return;
}
if let Ok(mut_last_logs) = &mut self.last_logs.try_write() {
mut_last_logs.insert(output.clone(), Instant::now());
}
self.db.admin.send(AdminCommand::SendTextMessage(
message::TextMessageEventContent {
body: output,
formatted: None,
relates_to: None,
},
));
}
}
fn flush(&self) {}
}