Skip to main content

systemprompt_logging/models/
log_entry.rs

1//! Core log-record types.
2//!
3//! [`LogEntry`] is the persisted log row; [`LogActor`] bundles the mandatory
4//! attribution triple (user, session, trace) every entry must carry, with
5//! [`LogActor::platform`] resolving the system owner for originator-less
6//! platform telemetry. Optional task/context/client identifiers are layered on
7//! via the builder methods.
8//!
9//! Copyright (c) systemprompt.io — Business Source License 1.1.
10//! See <https://systemprompt.io> for licensing details.
11
12use chrono::{DateTime, Utc};
13use serde::{Deserialize, Serialize};
14use systemprompt_identifiers::{LogId, SessionId, TraceId, UserId};
15
16use super::{LogLevel, LoggingError};
17use crate::attribution::{LogAttributionUnset, platform_owner_id};
18
19/// Mandatory attribution for every log row: who did the work, in which
20/// session, on which trace. Bundled so every `LogEntry::new` call carries
21/// the full triple instead of relying on hidden defaults.
22#[expect(
23    clippy::struct_field_names,
24    reason = "the `_id` suffix is load-bearing — it pairs each field with its typed identifier \
25              and matches the LogEntry field names so the constructor reads `entry.user_id = \
26              actor.user_id`"
27)]
28#[derive(Debug, Clone)]
29pub struct LogActor {
30    pub user_id: UserId,
31    pub session_id: SessionId,
32    pub trace_id: TraceId,
33}
34
35impl LogActor {
36    #[must_use]
37    pub const fn new(user_id: UserId, session_id: SessionId, trace_id: TraceId) -> Self {
38        Self {
39            user_id,
40            session_id,
41            trace_id,
42        }
43    }
44
45    pub fn platform(trace_id: TraceId) -> Result<Self, LogAttributionUnset> {
46        Ok(Self {
47            user_id: platform_owner_id()?.clone(),
48            session_id: SessionId::system(),
49            trace_id,
50        })
51    }
52}
53
54#[derive(Debug, Clone, Serialize, Deserialize)]
55pub struct LogEntry {
56    pub id: LogId,
57    pub timestamp: DateTime<Utc>,
58    pub level: LogLevel,
59    pub module: String,
60    pub message: String,
61    pub metadata: Option<serde_json::Value>,
62    pub user_id: UserId,
63    pub session_id: SessionId,
64    pub task_id: Option<systemprompt_identifiers::TaskId>,
65    pub trace_id: TraceId,
66    pub context_id: Option<systemprompt_identifiers::ContextId>,
67    pub client_id: Option<systemprompt_identifiers::ClientId>,
68}
69
70impl LogEntry {
71    pub fn new(
72        level: LogLevel,
73        module: impl Into<String>,
74        message: impl Into<String>,
75        actor: LogActor,
76    ) -> Self {
77        Self {
78            id: LogId::generate(),
79            timestamp: Utc::now(),
80            level,
81            module: module.into(),
82            message: message.into(),
83            metadata: None,
84            user_id: actor.user_id,
85            session_id: actor.session_id,
86            task_id: None,
87            trace_id: actor.trace_id,
88            context_id: None,
89            client_id: None,
90        }
91    }
92
93    #[must_use]
94    pub fn with_metadata(mut self, metadata: serde_json::Value) -> Self {
95        self.metadata = Some(metadata);
96        self
97    }
98
99    #[must_use]
100    pub fn with_task_id(mut self, task_id: systemprompt_identifiers::TaskId) -> Self {
101        self.task_id = Some(task_id);
102        self
103    }
104
105    #[must_use]
106    pub fn with_context_id(mut self, context_id: systemprompt_identifiers::ContextId) -> Self {
107        self.context_id = Some(context_id);
108        self
109    }
110
111    #[must_use]
112    pub fn with_client_id(mut self, client_id: systemprompt_identifiers::ClientId) -> Self {
113        self.client_id = Some(client_id);
114        self
115    }
116
117    pub fn validate(&self) -> Result<(), LoggingError> {
118        if self.module.is_empty() {
119            return Err(LoggingError::EmptyModuleName);
120        }
121        if self.message.is_empty() {
122            return Err(LoggingError::EmptyMessage);
123        }
124        if let Some(metadata) = &self.metadata
125            && !metadata.is_object()
126            && !metadata.is_array()
127            && !metadata.is_string()
128            && !metadata.is_null()
129        {
130            return Err(LoggingError::InvalidMetadata);
131        }
132        Ok(())
133    }
134}
135
136impl std::fmt::Display for LogEntry {
137    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
138        let level_str = match self.level {
139            LogLevel::Error => "ERROR",
140            LogLevel::Warn => "WARN ",
141            LogLevel::Info => "INFO ",
142            LogLevel::Debug => "DEBUG",
143            LogLevel::Trace => "TRACE",
144        };
145
146        let timestamp_str = self.timestamp.format("%H:%M:%S");
147
148        if let Some(metadata) = &self.metadata {
149            write!(
150                f,
151                "{} [{}] {}: {} {}",
152                timestamp_str,
153                level_str,
154                self.module,
155                self.message,
156                serde_json::to_string(metadata).unwrap_or_else(|_| String::new())
157            )
158        } else {
159            write!(
160                f,
161                "{} [{}] {}: {}",
162                timestamp_str, level_str, self.module, self.message
163            )
164        }
165    }
166}