Skip to main content

eventail/endpoint/
gelf.rs

1//! GELF support
2use std::collections::HashMap;
3use std::time::SystemTime;
4
5use serde::Serialize;
6use serde_json::Value;
7
8/// Syslog Criticity level
9#[derive(Debug)]
10pub enum Criticity {
11    Emergency,
12    Alert,
13    Critical,
14    Error,
15    Warning,
16    Notice,
17    Info,
18    Debug,
19}
20
21impl Criticity {
22    /// Criticity as a human readable label
23    pub fn label(&self) -> &'static str {
24        match self {
25            Self::Emergency => "EMERGENCY",
26            Self::Alert => "ALERT",
27            Self::Critical => "CRITICAL",
28            Self::Error => "ERROR",
29            Self::Warning => "WARNING",
30            Self::Notice => "NOTICE",
31            Self::Info => "INFO",
32            Self::Debug => "DEBUG",
33        }
34    }
35}
36
37pub type ExtraFields = HashMap<String, Value>;
38
39/// The GELF Payload we use for Service Logging, including custom fields
40#[derive(Debug, Serialize)]
41pub struct GelfPayload<'a> {
42    version: &'a str,
43    short_message: &'a str,
44    full_message: &'a str,
45    level: u8,
46    #[serde(rename = "_levelname")]
47    levelname: &'a str,
48    host: &'a str,
49    timestamp: f64,
50    #[serde(rename = "_conversation_id")]
51    conversation_id: &'a str,
52    #[serde(rename = "_logical_service")]
53    logical_service: &'a str,
54    #[serde(rename = "_worker_pid")]
55    worker_pid: u32,
56    #[serde(flatten)]
57    extra: ExtraFields,
58}
59
60impl<'a> GelfPayload<'a> {
61    pub fn new(
62        criticity: Criticity,
63        short_message: &'a str,
64        full_message: &'a str,
65        conversation_id: &'a str,
66        logical_service: &'a str,
67        host: &'a str,
68        extra: ExtraFields,
69    ) -> Self {
70        let mut escaped_extra: ExtraFields = HashMap::with_capacity(extra.len());
71        for (key, value) in extra {
72            escaped_extra.insert(format!("_{key}"), value);
73        }
74        Self {
75            version: "1.1",
76            short_message,
77            full_message,
78            levelname: criticity.label(),
79            level: criticity as u8,
80            conversation_id,
81            logical_service,
82            worker_pid: std::process::id(),
83            host,
84            timestamp: SystemTime::now()
85                .duration_since(SystemTime::UNIX_EPOCH)
86                .unwrap()
87                .as_millis() as f64
88                / 1000.0,
89            extra: escaped_extra,
90        }
91    }
92
93    pub fn routing_key(&self) -> String {
94        format!("{}.{}", self.logical_service, self.levelname)
95    }
96}