use std::collections::BTreeMap;
use std::fmt;
use std::time::{SystemTime, UNIX_EPOCH};
use serde_json::{Map, Number, Value};
use crate::core::{Error, Result};
use crate::logging::{AttrValue, Attributes, LogRecord, Severity};
pub const GELF_VERSION: &str = "1.1";
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(u8)]
pub enum GelfLevel {
Emergency = 0,
Alert = 1,
Critical = 2,
Error = 3,
Warning = 4,
Notice = 5,
Informational = 6,
Debug = 7,
}
impl GelfLevel {
pub fn number(self) -> u8 {
self as u8
}
pub fn from_number(n: i64) -> Result<GelfLevel> {
Ok(match n {
0 => GelfLevel::Emergency,
1 => GelfLevel::Alert,
2 => GelfLevel::Critical,
3 => GelfLevel::Error,
4 => GelfLevel::Warning,
5 => GelfLevel::Notice,
6 => GelfLevel::Informational,
7 => GelfLevel::Debug,
_ => return Err(Error::validation("gelf: level must be an integer 0..7")),
})
}
}
pub fn severity_to_gelf_level(severity: Severity) -> GelfLevel {
match severity {
Severity::Trace | Severity::Debug => GelfLevel::Debug,
Severity::Info => GelfLevel::Informational,
Severity::Warn => GelfLevel::Warning,
Severity::Error => GelfLevel::Error,
Severity::Fatal => GelfLevel::Critical,
}
}
pub fn gelf_level_to_severity(level: i64) -> Severity {
match level {
i64::MIN..=2 => Severity::Fatal,
3 => Severity::Error,
4 => Severity::Warn,
5 | 6 => Severity::Info,
_ => Severity::Debug,
}
}
fn is_key_char(c: char) -> bool {
c.is_ascii_alphanumeric() || matches!(c, '_' | '.' | '-')
}
pub fn gelf_field_key(name: &str) -> String {
if name == "id" {
return "_attr_id".to_owned();
}
let mut out = String::with_capacity(name.len() + 1);
out.push('_');
out.extend(name.chars().map(|c| if is_key_char(c) { c } else { '_' }));
out
}
pub fn gelf_field_value(value: &AttrValue) -> Option<Value> {
match value {
Value::Null => None,
Value::Bool(b) => Some(Value::String(b.to_string())),
Value::String(_) | Value::Number(_) => Some(value.clone()),
Value::Array(_) | Value::Object(_) => Some(Value::String(value.to_string())),
}
}
pub fn validate_gelf_field_key(key: &str) -> Result<String> {
let name = key.strip_prefix('_').unwrap_or(key);
if name.is_empty() || !name.chars().all(is_key_char) {
return Err(Error::validation(format!(
"gelf: invalid additional field key {key:?} (allowed: letters, digits, _ . -)"
)));
}
if name == "id" {
return Err(Error::validation(
"gelf: additional field \"_id\" is reserved",
));
}
Ok(format!("_{name}"))
}
pub fn gelf_timestamp(t: SystemTime) -> Number {
let ms = match t.duration_since(UNIX_EPOCH) {
Ok(d) => d.as_millis() as f64,
Err(e) => -(e.duration().as_millis() as f64),
};
Number::from_f64(ms / 1000.0).unwrap_or_else(|| Number::from(0))
}
#[derive(Debug, Clone, Default, PartialEq)]
pub struct GelfMessageOptions {
pub host: String,
pub short_message: String,
pub full_message: Option<String>,
pub timestamp: Option<SystemTime>,
pub level: Option<GelfLevel>,
pub fields: Attributes,
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct FromLogRecordOptions {
pub host: Option<String>,
}
#[derive(Debug, Clone, PartialEq)]
pub struct GelfMessage {
host: String,
short_message: String,
full_message: Option<String>,
timestamp: Option<SystemTime>,
level: Option<GelfLevel>,
fields: BTreeMap<String, Value>,
}
pub(crate) fn local_hostname() -> String {
let from_file = |p: &str| {
std::fs::read_to_string(p)
.ok()
.map(|s| s.trim().to_owned())
.filter(|s| !s.is_empty())
};
from_file("/proc/sys/kernel/hostname")
.or_else(|| from_file("/etc/hostname"))
.or_else(|| std::env::var("HOSTNAME").ok().filter(|s| !s.is_empty()))
.or_else(|| std::env::var("COMPUTERNAME").ok().filter(|s| !s.is_empty()))
.unwrap_or_else(|| "unknown".to_owned())
}
impl GelfMessage {
pub fn new(opts: GelfMessageOptions) -> Result<GelfMessage> {
if opts.host.trim().is_empty() {
return Err(Error::validation("gelf: host must not be blank"));
}
if opts.short_message.trim().is_empty() {
return Err(Error::validation("gelf: shortMessage must not be blank"));
}
let mut m = GelfMessage {
host: opts.host,
short_message: opts.short_message,
full_message: opts.full_message.filter(|s| !s.is_empty()),
timestamp: opts.timestamp,
level: opts.level,
fields: BTreeMap::new(),
};
for (k, v) in &opts.fields {
m.set_field(k, v.clone())?;
}
Ok(m)
}
pub fn simple(host: impl Into<String>, short_message: impl Into<String>) -> Result<Self> {
Self::new(GelfMessageOptions {
host: host.into(),
short_message: short_message.into(),
..GelfMessageOptions::default()
})
}
pub fn set_field(&mut self, key: &str, value: impl Into<AttrValue>) -> Result<()> {
let wire = validate_gelf_field_key(key)?;
match gelf_field_value(&value.into()) {
Some(v) => {
self.fields.insert(wire, v);
}
None => {
self.fields.remove(&wire);
}
}
Ok(())
}
pub fn with_field(mut self, key: &str, value: impl Into<AttrValue>) -> Result<Self> {
self.set_field(key, value)?;
Ok(self)
}
pub fn host(&self) -> &str {
&self.host
}
pub fn short_message(&self) -> &str {
&self.short_message
}
pub fn full_message(&self) -> Option<&str> {
self.full_message.as_deref()
}
pub fn timestamp(&self) -> Option<SystemTime> {
self.timestamp
}
pub fn level(&self) -> Option<GelfLevel> {
self.level
}
pub fn fields(&self) -> &BTreeMap<String, Value> {
&self.fields
}
pub fn to_value(&self) -> Value {
let mut doc: Map<String, Value> = self
.fields
.iter()
.map(|(k, v)| (k.clone(), v.clone()))
.collect();
doc.insert("version".into(), Value::String(GELF_VERSION.into()));
doc.insert("host".into(), Value::String(self.host.clone()));
doc.insert(
"short_message".into(),
Value::String(self.short_message.clone()),
);
if let Some(f) = &self.full_message {
doc.insert("full_message".into(), Value::String(f.clone()));
}
if let Some(t) = self.timestamp {
doc.insert("timestamp".into(), Value::Number(gelf_timestamp(t)));
}
if let Some(l) = self.level {
doc.insert("level".into(), Value::from(l.number()));
}
Value::Object(doc)
}
pub fn encode(&self) -> Vec<u8> {
self.to_value().to_string().into_bytes()
}
pub fn from_log_record(record: &LogRecord, opts: &FromLogRecordOptions) -> GelfMessage {
let host = record
.resource
.get("host.name")
.and_then(Value::as_str)
.filter(|h| !h.trim().is_empty())
.map(str::to_owned)
.or_else(|| opts.host.clone().filter(|h| !h.trim().is_empty()))
.unwrap_or_else(local_hostname);
let body = if record.body.trim().is_empty() {
"-".to_owned()
} else {
record.body.clone()
};
let mut m = GelfMessage {
host,
short_message: body,
full_message: None,
timestamp: Some(record.timestamp),
level: Some(severity_to_gelf_level(record.severity)),
fields: BTreeMap::new(),
};
let mut put = |name: &str, value: &AttrValue| {
if name.is_empty() {
return;
}
if let Some(v) = gelf_field_value(value) {
m.fields.insert(gelf_field_key(name), v);
}
};
for (k, v) in flatten_attributes(&record.resource) {
if k != "host.name" {
put(&k, &v);
}
}
for (k, v) in &record.attributes {
put(k, v);
}
if let Some(t) = record.trace_id.as_deref().filter(|t| !t.is_empty()) {
put("trace_id", &Value::String(t.to_owned()));
}
if let Some(s) = record.span_id.as_deref().filter(|s| !s.is_empty()) {
put("span_id", &Value::String(s.to_owned()));
}
if let Some(f) = record.trace_flags {
put("trace_flags", &Value::from(f));
}
m
}
}
impl fmt::Display for GelfMessage {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.to_value())
}
}
pub fn flatten_attributes(attributes: &Attributes) -> Attributes {
fn walk(out: &mut Attributes, prefix: &str, map: &mut dyn Iterator<Item = (&String, &Value)>) {
for (k, v) in map {
let key = if prefix.is_empty() {
k.clone()
} else {
format!("{prefix}.{k}")
};
match v {
Value::Object(inner) => walk(out, &key, &mut inner.iter()),
other => {
out.insert(key, other.clone());
}
}
}
}
let mut out = Attributes::new();
walk(&mut out, "", &mut attributes.iter());
out
}