~ knotless Search/
↑↓ move↵ open⇧↵ all results

johnandersen777.bsky.social/vuln-notif

0
0
main
132 lines · 3.3 KB Raw History
use std::sync::{Arc, Mutex};

use chrono::Utc;
use serde_json::{Map, Value};

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum Level {
    Debug,
    Info,
    Warn,
    Error,
}

impl Level {
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Debug => "debug",
            Self::Info => "info",
            Self::Warn => "warn",
            Self::Error => "error",
        }
    }

    pub fn parse_level(value: &str) -> Self {
        match value.to_ascii_lowercase().as_str() {
            "debug" => Self::Debug,
            "warn" | "warning" => Self::Warn,
            "error" => Self::Error,
            _ => Self::Info,
        }
    }
}

pub trait LogSink: Send + Sync {
    fn write_line(&self, line: &str);
}

pub struct StderrSink;

impl LogSink for StderrSink {
    fn write_line(&self, line: &str) {
        eprintln!("{line}");
    }
}

#[derive(Default)]
pub struct CaptureSink {
    lines: Mutex<Vec<String>>,
}

impl CaptureSink {
    pub fn lines(&self) -> Vec<String> {
        self.lines.lock().expect("capture sink poisoned").clone()
    }
}

impl LogSink for CaptureSink {
    fn write_line(&self, line: &str) {
        self.lines
            .lock()
            .expect("capture sink poisoned")
            .push(line.to_owned());
    }
}

#[derive(Clone)]
pub struct Logger {
    sink: Arc<dyn LogSink>,
    min_level: Level,
    target: String,
}

impl Logger {
    pub fn new(sink: Arc<dyn LogSink>, min_level: Level) -> Self {
        Self {
            sink,
            min_level,
            target: "vuln-notif".to_owned(),
        }
    }

    pub fn stderr(min_level: Level) -> Self {
        Self::new(Arc::new(StderrSink), min_level)
    }

    pub fn with_target(mut self, target: impl Into<String>) -> Self {
        self.target = target.into();
        self
    }

    pub fn debug(&self, event: &str, scope: Option<&str>, fields: Value) {
        self.log(Level::Debug, event, scope, fields);
    }

    pub fn info(&self, event: &str, scope: Option<&str>, fields: Value) {
        self.log(Level::Info, event, scope, fields);
    }

    pub fn warn(&self, event: &str, scope: Option<&str>, fields: Value) {
        self.log(Level::Warn, event, scope, fields);
    }

    pub fn error(&self, event: &str, scope: Option<&str>, fields: Value) {
        self.log(Level::Error, event, scope, fields);
    }

    pub fn log(&self, level: Level, event: &str, scope: Option<&str>, fields: Value) {
        if level < self.min_level {
            return;
        }
        let mut map = Map::new();
        map.insert(
            "ts".into(),
            Value::String(Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Millis, true)),
        );
        map.insert("level".into(), Value::String(level.as_str().into()));
        map.insert("target".into(), Value::String(self.target.clone()));
        map.insert("event".into(), Value::String(event.into()));
        if let Some(scope) = scope {
            map.insert("scope".into(), Value::String(scope.into()));
        }
        if let Value::Object(fields) = fields {
            for (key, value) in fields {
                if matches!(key.as_str(), "ts" | "level" | "target" | "event" | "scope") {
                    continue;
                }
                map.insert(key, value);
            }
        }
        self.sink.write_line(&Value::Object(map).to_string());
    }
}