1use std::collections::BTreeMap;
5use std::fmt;
6use std::time::{SystemTime, UNIX_EPOCH};
7
8use serde_json::{Map, Number, Value};
9
10use crate::core::{Error, Result};
11use crate::logging::{AttrValue, Attributes, LogRecord, Severity};
12
13pub const GELF_VERSION: &str = "1.1";
15
16#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
18#[repr(u8)]
19pub enum GelfLevel {
20 Emergency = 0,
22 Alert = 1,
24 Critical = 2,
26 Error = 3,
28 Warning = 4,
30 Notice = 5,
32 Informational = 6,
34 Debug = 7,
36}
37
38impl GelfLevel {
39 pub fn number(self) -> u8 {
41 self as u8
42 }
43
44 pub fn from_number(n: i64) -> Result<GelfLevel> {
46 Ok(match n {
47 0 => GelfLevel::Emergency,
48 1 => GelfLevel::Alert,
49 2 => GelfLevel::Critical,
50 3 => GelfLevel::Error,
51 4 => GelfLevel::Warning,
52 5 => GelfLevel::Notice,
53 6 => GelfLevel::Informational,
54 7 => GelfLevel::Debug,
55 _ => return Err(Error::validation("gelf: level must be an integer 0..7")),
56 })
57 }
58}
59
60pub fn severity_to_gelf_level(severity: Severity) -> GelfLevel {
63 match severity {
64 Severity::Trace | Severity::Debug => GelfLevel::Debug,
65 Severity::Info => GelfLevel::Informational,
66 Severity::Warn => GelfLevel::Warning,
67 Severity::Error => GelfLevel::Error,
68 Severity::Fatal => GelfLevel::Critical,
69 }
70}
71
72pub fn gelf_level_to_severity(level: i64) -> Severity {
75 match level {
76 i64::MIN..=2 => Severity::Fatal,
77 3 => Severity::Error,
78 4 => Severity::Warn,
79 5 | 6 => Severity::Info,
80 _ => Severity::Debug,
81 }
82}
83
84fn is_key_char(c: char) -> bool {
85 c.is_ascii_alphanumeric() || matches!(c, '_' | '.' | '-')
86}
87
88pub fn gelf_field_key(name: &str) -> String {
92 if name == "id" {
93 return "_attr_id".to_owned();
94 }
95 let mut out = String::with_capacity(name.len() + 1);
96 out.push('_');
97 out.extend(name.chars().map(|c| if is_key_char(c) { c } else { '_' }));
98 out
99}
100
101pub fn gelf_field_value(value: &AttrValue) -> Option<Value> {
105 match value {
106 Value::Null => None,
107 Value::Bool(b) => Some(Value::String(b.to_string())),
108 Value::String(_) | Value::Number(_) => Some(value.clone()),
109 Value::Array(_) | Value::Object(_) => Some(Value::String(value.to_string())),
110 }
111}
112
113pub fn validate_gelf_field_key(key: &str) -> Result<String> {
116 let name = key.strip_prefix('_').unwrap_or(key);
117 if name.is_empty() || !name.chars().all(is_key_char) {
118 return Err(Error::validation(format!(
119 "gelf: invalid additional field key {key:?} (allowed: letters, digits, _ . -)"
120 )));
121 }
122 if name == "id" {
123 return Err(Error::validation(
124 "gelf: additional field \"_id\" is reserved",
125 ));
126 }
127 Ok(format!("_{name}"))
128}
129
130pub fn gelf_timestamp(t: SystemTime) -> Number {
133 let ms = match t.duration_since(UNIX_EPOCH) {
134 Ok(d) => d.as_millis() as f64,
135 Err(e) => -(e.duration().as_millis() as f64),
136 };
137 Number::from_f64(ms / 1000.0).unwrap_or_else(|| Number::from(0))
138}
139
140#[derive(Debug, Clone, Default, PartialEq)]
142pub struct GelfMessageOptions {
143 pub host: String,
145 pub short_message: String,
147 pub full_message: Option<String>,
149 pub timestamp: Option<SystemTime>,
151 pub level: Option<GelfLevel>,
153 pub fields: Attributes,
155}
156
157#[derive(Debug, Clone, Default, PartialEq, Eq)]
159pub struct FromLogRecordOptions {
160 pub host: Option<String>,
162}
163
164#[derive(Debug, Clone, PartialEq)]
168pub struct GelfMessage {
169 host: String,
170 short_message: String,
171 full_message: Option<String>,
172 timestamp: Option<SystemTime>,
173 level: Option<GelfLevel>,
174 fields: BTreeMap<String, Value>,
175}
176
177pub(crate) fn local_hostname() -> String {
179 let from_file = |p: &str| {
180 std::fs::read_to_string(p)
181 .ok()
182 .map(|s| s.trim().to_owned())
183 .filter(|s| !s.is_empty())
184 };
185 from_file("/proc/sys/kernel/hostname")
186 .or_else(|| from_file("/etc/hostname"))
187 .or_else(|| std::env::var("HOSTNAME").ok().filter(|s| !s.is_empty()))
188 .or_else(|| std::env::var("COMPUTERNAME").ok().filter(|s| !s.is_empty()))
189 .unwrap_or_else(|| "unknown".to_owned())
190}
191
192impl GelfMessage {
193 pub fn new(opts: GelfMessageOptions) -> Result<GelfMessage> {
196 if opts.host.trim().is_empty() {
197 return Err(Error::validation("gelf: host must not be blank"));
198 }
199 if opts.short_message.trim().is_empty() {
200 return Err(Error::validation("gelf: shortMessage must not be blank"));
201 }
202 let mut m = GelfMessage {
203 host: opts.host,
204 short_message: opts.short_message,
205 full_message: opts.full_message.filter(|s| !s.is_empty()),
206 timestamp: opts.timestamp,
207 level: opts.level,
208 fields: BTreeMap::new(),
209 };
210 for (k, v) in &opts.fields {
211 m.set_field(k, v.clone())?;
212 }
213 Ok(m)
214 }
215
216 pub fn simple(host: impl Into<String>, short_message: impl Into<String>) -> Result<Self> {
218 Self::new(GelfMessageOptions {
219 host: host.into(),
220 short_message: short_message.into(),
221 ..GelfMessageOptions::default()
222 })
223 }
224
225 pub fn set_field(&mut self, key: &str, value: impl Into<AttrValue>) -> Result<()> {
229 let wire = validate_gelf_field_key(key)?;
230 match gelf_field_value(&value.into()) {
231 Some(v) => {
232 self.fields.insert(wire, v);
233 }
234 None => {
235 self.fields.remove(&wire);
236 }
237 }
238 Ok(())
239 }
240
241 pub fn with_field(mut self, key: &str, value: impl Into<AttrValue>) -> Result<Self> {
243 self.set_field(key, value)?;
244 Ok(self)
245 }
246
247 pub fn host(&self) -> &str {
249 &self.host
250 }
251 pub fn short_message(&self) -> &str {
253 &self.short_message
254 }
255 pub fn full_message(&self) -> Option<&str> {
257 self.full_message.as_deref()
258 }
259 pub fn timestamp(&self) -> Option<SystemTime> {
261 self.timestamp
262 }
263 pub fn level(&self) -> Option<GelfLevel> {
265 self.level
266 }
267 pub fn fields(&self) -> &BTreeMap<String, Value> {
269 &self.fields
270 }
271
272 pub fn to_value(&self) -> Value {
275 let mut doc: Map<String, Value> = self
276 .fields
277 .iter()
278 .map(|(k, v)| (k.clone(), v.clone()))
279 .collect();
280 doc.insert("version".into(), Value::String(GELF_VERSION.into()));
281 doc.insert("host".into(), Value::String(self.host.clone()));
282 doc.insert(
283 "short_message".into(),
284 Value::String(self.short_message.clone()),
285 );
286 if let Some(f) = &self.full_message {
287 doc.insert("full_message".into(), Value::String(f.clone()));
288 }
289 if let Some(t) = self.timestamp {
290 doc.insert("timestamp".into(), Value::Number(gelf_timestamp(t)));
291 }
292 if let Some(l) = self.level {
293 doc.insert("level".into(), Value::from(l.number()));
294 }
295 Value::Object(doc)
296 }
297
298 pub fn encode(&self) -> Vec<u8> {
300 self.to_value().to_string().into_bytes()
301 }
302
303 pub fn from_log_record(record: &LogRecord, opts: &FromLogRecordOptions) -> GelfMessage {
310 let host = record
311 .resource
312 .get("host.name")
313 .and_then(Value::as_str)
314 .filter(|h| !h.trim().is_empty())
315 .map(str::to_owned)
316 .or_else(|| opts.host.clone().filter(|h| !h.trim().is_empty()))
317 .unwrap_or_else(local_hostname);
318 let body = if record.body.trim().is_empty() {
319 "-".to_owned()
320 } else {
321 record.body.clone()
322 };
323 let mut m = GelfMessage {
324 host,
325 short_message: body,
326 full_message: None,
327 timestamp: Some(record.timestamp),
328 level: Some(severity_to_gelf_level(record.severity)),
329 fields: BTreeMap::new(),
330 };
331 let mut put = |name: &str, value: &AttrValue| {
332 if name.is_empty() {
333 return;
334 }
335 if let Some(v) = gelf_field_value(value) {
336 m.fields.insert(gelf_field_key(name), v);
337 }
338 };
339 for (k, v) in flatten_attributes(&record.resource) {
340 if k != "host.name" {
341 put(&k, &v);
342 }
343 }
344 for (k, v) in &record.attributes {
345 put(k, v);
346 }
347 if let Some(t) = record.trace_id.as_deref().filter(|t| !t.is_empty()) {
348 put("trace_id", &Value::String(t.to_owned()));
349 }
350 if let Some(s) = record.span_id.as_deref().filter(|s| !s.is_empty()) {
351 put("span_id", &Value::String(s.to_owned()));
352 }
353 if let Some(f) = record.trace_flags {
354 put("trace_flags", &Value::from(f));
355 }
356 m
357 }
358}
359
360impl fmt::Display for GelfMessage {
361 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
362 write!(f, "{}", self.to_value())
363 }
364}
365
366pub fn flatten_attributes(attributes: &Attributes) -> Attributes {
368 fn walk(out: &mut Attributes, prefix: &str, map: &mut dyn Iterator<Item = (&String, &Value)>) {
369 for (k, v) in map {
370 let key = if prefix.is_empty() {
371 k.clone()
372 } else {
373 format!("{prefix}.{k}")
374 };
375 match v {
376 Value::Object(inner) => walk(out, &key, &mut inner.iter()),
377 other => {
378 out.insert(key, other.clone());
379 }
380 }
381 }
382 }
383 let mut out = Attributes::new();
384 walk(&mut out, "", &mut attributes.iter());
385 out
386}