Initial commit

This commit is contained in:
2022-11-12 01:37:09 +01:00
commit d180e72373
16 changed files with 3341 additions and 0 deletions

61
snitchlib/src/lib.rs Normal file
View File

@ -0,0 +1,61 @@
use log::{Level, Log, Metadata, Record};
use reqwest::blocking;
mod message;
pub use message::{LogMsg, Severity};
pub struct SnitchLogger<L: Log> {
wrapped: L,
url: String,
service_name: String,
}
impl<L: Log> SnitchLogger<L> {
pub fn new(wrapped: L, url: impl Into<String>, service_name: impl Into<String>) -> Self {
SnitchLogger {
wrapped,
url: url.into(),
service_name: service_name.into(),
}
}
}
impl<L: Log> Log for SnitchLogger<L> {
fn enabled(&self, metadata: &Metadata) -> bool {
self.wrapped.enabled(metadata) || metadata.level() <= Level::Warn
}
fn log(&self, record: &Record) {
eprintln!("log called");
self.wrapped.log(record);
let severity = match record.metadata().level() {
Level::Error => Severity::Error,
Level::Warn => Severity::Warning,
_ => return,
};
let record = LogMsg {
severity,
file: record.file().map(String::from),
line: record.line(),
..LogMsg::new(self.service_name.clone(), record.args().to_string())
};
let client = blocking::Client::new();
if let Err(e) = client.post(&self.url).json(&record).send() {
// TODO: log error (without sending it)
eprintln!("failed to send log record: {e:?}");
}
}
fn flush(&self) {
self.wrapped.flush();
}
}
impl<L: Log> Drop for SnitchLogger<L> {
fn drop(&mut self) {
self.flush();
}
}

39
snitchlib/src/message.rs Normal file
View File

@ -0,0 +1,39 @@
use chrono::{DateTime, Local};
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum Severity {
Fatal,
Error,
Warning,
}
#[derive(Clone, Serialize, Deserialize)]
pub struct LogMsg {
/// The time that the error was reported.
pub time: DateTime<Local>,
pub severity: Severity,
/// The service which reported the error.
pub service: String,
/// The log message.
pub message: String,
pub file: Option<String>,
pub line: Option<u32>,
}
impl LogMsg {
pub fn new(service: String, message: String) -> Self {
Self {
time: Local::now(),
severity: Severity::Error,
service,
message,
file: None,
line: None,
}
}
}