grafbase_sdk/host_io/logger/
file.rs

1//! File logging functionality with support for log rotation.
2
3use std::path::PathBuf;
4
5use crate::{SdkError, wit};
6
7/// A file logger that writes serialized messages to a file with optional rotation.
8pub struct FileLogger(wit::FileLogger);
9
10impl FileLogger {
11    /// Creates a new file logger with the specified path and rotation strategy.
12    pub fn new(path: impl Into<PathBuf>, rotation: Option<LogRotation>) -> Result<Self, SdkError> {
13        let opts = wit::FileLoggerOptions {
14            path: path.into().to_string_lossy().into_owned(),
15            rotate: rotation.map(Into::into),
16        };
17
18        let logger = wit::FileLogger::init(&opts)?;
19
20        Ok(Self(logger))
21    }
22
23    /// Logs a JSON-serialized message to the file.
24    ///
25    /// This method serializes the provided message to JSON format and writes it to the log file.
26    pub fn log_json<S>(&self, message: S) -> Result<(), SdkError>
27    where
28        S: serde::Serialize,
29    {
30        let json = serde_json::to_vec(&message)?;
31        self.log(&json)
32    }
33
34    /// Logs a message to the file. The caller decides the encoding of the message.
35    pub fn log(&self, message: &[u8]) -> Result<(), SdkError> {
36        self.0.log(message)?;
37
38        Ok(())
39    }
40}
41
42/// Log rotation strategies for file logging.
43pub enum LogRotation {
44    /// Rotate when the log file reaches the specified size in bytes.
45    Size(u64),
46    /// Rotate the log file every minute.
47    Minutely,
48    /// Rotate the log file every hour.
49    Hourly,
50    /// Rotate the log file every day.
51    Daily,
52    /// Rotate the log file every week.
53    Weekly,
54    /// Rotate the log file every month.
55    Monthly,
56    /// Rotate the log file every year.
57    Yearly,
58}
59
60impl From<LogRotation> for wit::FileLoggerRotation {
61    fn from(value: LogRotation) -> Self {
62        match value {
63            LogRotation::Size(size) => wit::FileLoggerRotation::Size(size),
64            LogRotation::Minutely => wit::FileLoggerRotation::Minutely,
65            LogRotation::Hourly => wit::FileLoggerRotation::Hourly,
66            LogRotation::Daily => wit::FileLoggerRotation::Daily,
67            LogRotation::Weekly => wit::FileLoggerRotation::Weekly,
68            LogRotation::Monthly => wit::FileLoggerRotation::Monthly,
69            LogRotation::Yearly => wit::FileLoggerRotation::Yearly,
70        }
71    }
72}