use std::collections::BTreeMap;
use std::fmt;
use std::str::FromStr;
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use crate::core::{Error, Result};
pub type AttrValue = serde_json::Value;
pub type Attributes = BTreeMap<String, AttrValue>;
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
#[repr(u8)]
pub enum Severity {
Trace = 1,
Debug = 5,
#[default]
Info = 9,
Warn = 13,
Error = 17,
Fatal = 21,
}
impl Severity {
pub const ALL: [Severity; 6] = [
Severity::Trace,
Severity::Debug,
Severity::Info,
Severity::Warn,
Severity::Error,
Severity::Fatal,
];
pub fn number(self) -> u8 {
self as u8
}
pub fn text(self) -> &'static str {
match self {
Severity::Trace => "TRACE",
Severity::Debug => "DEBUG",
Severity::Info => "INFO",
Severity::Warn => "WARN",
Severity::Error => "ERROR",
Severity::Fatal => "FATAL",
}
}
pub fn from_number(n: u8) -> Severity {
match n {
1..=4 => Severity::Trace,
5..=8 => Severity::Debug,
13..=16 => Severity::Warn,
17..=20 => Severity::Error,
21..=u8::MAX => Severity::Fatal,
_ => Severity::Info,
}
}
}
impl fmt::Display for Severity {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.text())
}
}
impl FromStr for Severity {
type Err = Error;
fn from_str(s: &str) -> Result<Self> {
let t = s.trim();
if let Ok(n) = t.parse::<u8>() {
return Ok(Severity::from_number(n));
}
match t.to_ascii_lowercase().as_str() {
"trace" => Ok(Severity::Trace),
"debug" => Ok(Severity::Debug),
"info" | "information" | "notice" => Ok(Severity::Info),
"warn" | "warning" => Ok(Severity::Warn),
"error" | "err" => Ok(Severity::Error),
"fatal" | "critical" | "crit" | "panic" | "emergency" | "alert" => Ok(Severity::Fatal),
_ => Err(Error::validation(format!("unknown log severity {t:?}"))),
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct LogRecord {
pub timestamp: SystemTime,
pub observed_timestamp: Option<SystemTime>,
pub severity: Severity,
pub severity_text: String,
pub body: String,
pub attributes: Attributes,
pub resource: Attributes,
pub trace_id: Option<String>,
pub span_id: Option<String>,
pub trace_flags: Option<u8>,
}
impl LogRecord {
pub fn new(severity: Severity, body: impl Into<String>) -> Self {
LogRecord {
timestamp: SystemTime::now(),
observed_timestamp: None,
severity,
severity_text: severity.text().to_string(),
body: body.into(),
attributes: Attributes::new(),
resource: Attributes::new(),
trace_id: None,
span_id: None,
trace_flags: None,
}
}
pub fn with_attribute(mut self, key: impl Into<String>, value: impl Into<AttrValue>) -> Self {
self.attributes.insert(key.into(), value.into());
self
}
pub fn with_trace(mut self, trace_id: impl Into<String>, span_id: impl Into<String>) -> Self {
self.trace_id = Some(trace_id.into());
self.span_id = Some(span_id.into());
self
}
pub fn to_json_value(&self) -> serde_json::Value {
serde_json::to_value(self).unwrap_or(serde_json::Value::Null)
}
pub fn to_json(&self) -> String {
self.to_json_value().to_string()
}
pub fn from_json(text: &str) -> Result<Self> {
serde_json::from_str(text)
.map_err(|e| Error::validation(format!("invalid log record JSON: {e}")))
}
pub fn json_size(&self) -> usize {
serde_json::to_vec(self).map(|v| v.len()).unwrap_or(0)
}
pub fn contains_text(&self, needle: &str) -> bool {
fn walk(v: &AttrValue, needle: &str) -> bool {
match v {
AttrValue::String(s) => s.contains(needle),
AttrValue::Array(a) => a.iter().any(|x| walk(x, needle)),
AttrValue::Object(m) => m.values().any(|x| walk(x, needle)),
_ => false,
}
}
self.body.contains(needle) || self.attributes.values().any(|v| walk(v, needle))
}
}
#[derive(Debug, Clone, Default, PartialEq)]
pub struct LogInput {
pub message: String,
pub severity: Option<Severity>,
pub attributes: Attributes,
pub timestamp: Option<SystemTime>,
pub trace_id: Option<String>,
pub span_id: Option<String>,
}
impl LogInput {
pub fn new(message: impl Into<String>) -> Self {
LogInput {
message: message.into(),
..Default::default()
}
}
pub fn severity(mut self, severity: Severity) -> Self {
self.severity = Some(severity);
self
}
pub fn attribute(mut self, key: impl Into<String>, value: impl Into<AttrValue>) -> Self {
self.attributes.insert(key.into(), value.into());
self
}
pub fn attributes(mut self, attributes: Attributes) -> Self {
self.attributes = attributes;
self
}
pub fn timestamp(mut self, timestamp: SystemTime) -> Self {
self.timestamp = Some(timestamp);
self
}
pub fn trace(mut self, trace_id: impl Into<String>, span_id: impl Into<String>) -> Self {
self.trace_id = Some(trace_id.into());
self.span_id = Some(span_id.into());
self
}
}
impl From<&str> for LogInput {
fn from(message: &str) -> Self {
LogInput::new(message)
}
}
impl From<String> for LogInput {
fn from(message: String) -> Self {
LogInput::new(message)
}
}
pub fn format_timestamp(t: SystemTime) -> String {
let t = if t < UNIX_EPOCH { UNIX_EPOCH } else { t };
humantime::format_rfc3339_nanos(t).to_string()
}
pub fn parse_timestamp(s: &str) -> Result<SystemTime> {
let s = s.trim();
if let Ok(ns) = s.parse::<u64>() {
return Ok(UNIX_EPOCH + Duration::from_nanos(ns));
}
let bad = || Error::validation(format!("invalid timestamp {s:?}"));
let (base, offset_secs) = match s.char_indices().rev().find(|(_, c)| *c == '+' || *c == '-') {
Some((i, sign)) if i > 10 && s[i..].len() == 6 && &s[i + 3..i + 4] == ":" => {
let h: i64 = s[i + 1..i + 3].parse().map_err(|_| bad())?;
let m: i64 = s[i + 4..].parse().map_err(|_| bad())?;
let secs = h * 3600 + m * 60;
(
format!("{}Z", &s[..i]),
if sign == '+' { secs } else { -secs },
)
}
_ => (s.to_string(), 0),
};
let t = humantime::parse_rfc3339_weak(base.trim_end_matches('Z')).map_err(|_| bad())?;
let shifted = if offset_secs >= 0 {
t.checked_sub(Duration::from_secs(offset_secs as u64))
} else {
t.checked_add(Duration::from_secs(offset_secs.unsigned_abs()))
};
shifted.ok_or_else(bad)
}
#[derive(Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
struct WireRecord {
timestamp: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
observed_timestamp: Option<String>,
severity: u8,
severity_text: String,
body: serde_json::Value,
#[serde(default)]
attributes: Attributes,
#[serde(default)]
resource: Attributes,
#[serde(default, skip_serializing_if = "Option::is_none")]
trace_id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
span_id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
trace_flags: Option<u8>,
}
impl Serialize for LogRecord {
fn serialize<S: Serializer>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error> {
WireRecord {
timestamp: format_timestamp(self.timestamp),
observed_timestamp: self.observed_timestamp.map(format_timestamp),
severity: self.severity.number(),
severity_text: self.severity_text.clone(),
body: serde_json::Value::String(self.body.clone()),
attributes: self.attributes.clone(),
resource: self.resource.clone(),
trace_id: self.trace_id.clone(),
span_id: self.span_id.clone(),
trace_flags: self.trace_flags,
}
.serialize(serializer)
}
}
impl<'de> Deserialize<'de> for LogRecord {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> std::result::Result<Self, D::Error> {
let w = WireRecord::deserialize(deserializer)?;
let timestamp = parse_timestamp(&w.timestamp).map_err(serde::de::Error::custom)?;
let observed_timestamp = match &w.observed_timestamp {
Some(t) => Some(parse_timestamp(t).map_err(serde::de::Error::custom)?),
None => None,
};
let body = match w.body {
serde_json::Value::String(s) => s,
other => other.to_string(),
};
Ok(LogRecord {
timestamp,
observed_timestamp,
severity: Severity::from_number(w.severity),
severity_text: w.severity_text,
body,
attributes: w.attributes,
resource: w.resource,
trace_id: w.trace_id,
span_id: w.span_id,
trace_flags: w.trace_flags,
})
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn timestamp_offsets_and_nanos() {
let z = parse_timestamp("2026-01-02T03:04:05.5Z").unwrap();
assert_eq!(parse_timestamp("2026-01-02T05:04:05.5+02:00").unwrap(), z);
assert_eq!(parse_timestamp("2026-01-02T01:04:05.5-02:00").unwrap(), z);
assert_eq!(
parse_timestamp("1000000000").unwrap(),
UNIX_EPOCH + Duration::from_secs(1)
);
assert!(parse_timestamp("yesterday").is_err());
assert!(parse_timestamp("2026-01-02T05:04:05+xx:00").is_err());
assert!(parse_timestamp("2026-01-02T05:04:05+02:yy").is_err());
assert_eq!(
format_timestamp(UNIX_EPOCH - Duration::from_secs(5)),
"1970-01-01T00:00:00.000000000Z"
);
}
}