about summary refs log tree commit diff
path: root/corp/rih/backend/src/yandex_log.rs
blob: 64bb4ff97dc59cdfb335fa36e2bf2b2752760c03 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
//! Implements a `log::Log` logger that adheres to the structure
//! expected by Yandex Cloud Serverless logs.
//!
//! https://cloud.yandex.ru/docs/serverless-containers/concepts/logs

use log::{Level, Log};
use serde_json::json;

pub struct YandexCloudLogger;

pub const YANDEX_CLOUD_LOGGER: YandexCloudLogger = YandexCloudLogger;

fn level_map(level: &Level) -> &'static str {
    match level {
        Level::Error => "ERROR",
        Level::Warn => "WARN",
        Level::Info => "INFO",
        Level::Debug => "DEBUG",
        Level::Trace => "TRACE",
    }
}

impl Log for YandexCloudLogger {
    fn enabled(&self, _: &log::Metadata<'_>) -> bool {
        true
    }

    fn log(&self, record: &log::Record<'_>) {
        if !self.enabled(record.metadata()) {
            return;
        }

        eprintln!(
            "{}",
            json!({
                "level": level_map(&record.level()),
                "message": record.args().to_string(),
                "target": record.target(),
                "module": record.module_path(),
                "file": record.file(),
                "line": record.line(),
            })
        );
    }

    fn flush(&self) {}
}