Skip to main content

saluki_app/logging/
config.rs

1use std::fmt;
2
3use bytesize::ByteSize;
4use saluki_common::logging::parse_filter_directives;
5use saluki_error::{generic_error, ErrorContext as _, GenericError};
6use serde::Deserialize;
7use tracing::Level;
8use tracing_subscriber::filter::{LevelFilter, Targets};
9
10const DEFAULT_LOG_FILE_MAX_SIZE: ByteSize = ByteSize::mib(10);
11const DEFAULT_LOG_FILE_MAX_ROLLS: usize = 1;
12
13/// Logging configuration.
14///
15/// This is a plain value type. Callers construct instances directly, either via [`simple`] for a basic
16/// console-only configuration or via a translator that maps from the application's wider configuration into this
17/// type, applying any application-specific rules.
18///
19/// [`simple`]: LoggingConfiguration::simple
20pub struct LoggingConfiguration {
21    /// Verbosity directives (for example, `info`, `debug`, `saluki=trace`).
22    pub log_level: LogLevel,
23
24    /// Whether to emit log records as JSON instead of the default human-readable format.
25    pub log_format_json: bool,
26
27    /// Whether to use RFC 3339 timestamps (`2024-12-31T18:59:59.123456789-05:00`) in log output.
28    ///
29    /// When `false` (the default), timestamps use the legacy format (`2024-12-31 18:59:59 EST`). Both formats use the
30    /// system's local time zone.
31    ///
32    /// Defaults to `false`.
33    pub log_format_rfc3339: bool,
34
35    /// Whether to write log records to standard output.
36    pub log_to_console: bool,
37
38    /// Whether to write log records to syslog.
39    ///
40    /// Defaults to `false`. When this is `true` and [`syslog_uri`] is empty, callers should resolve the destination to
41    /// the platform's default local syslog URI before constructing the logging output stack.
42    ///
43    /// [`syslog_uri`]: LoggingConfiguration::syslog_uri
44    pub log_to_syslog: bool,
45
46    /// URI of the syslog destination.
47    ///
48    /// Defaults to an empty string. An empty value means "use the platform default" only when [`log_to_syslog`] is
49    /// enabled; otherwise it has no effect. Supported URI schemes are handled by the syslog output implementation.
50    ///
51    /// [`log_to_syslog`]: LoggingConfiguration::log_to_syslog
52    pub syslog_uri: String,
53
54    /// Whether to use the Agent's RFC-style syslog header.
55    ///
56    /// Defaults to `false`, which preserves the Agent's legacy syslog header format. Set this to `true` when the
57    /// receiving syslog daemon expects the Agent's RFC-style header.
58    pub syslog_rfc: bool,
59
60    /// Path to the log file to write to, or empty to disable file logging.
61    pub log_file: String,
62
63    /// Maximum size of a log file before it's rolled over.
64    pub log_file_max_size: ByteSize,
65
66    /// Maximum number of rolled-over log files to retain. `0` retains one.
67    pub log_file_max_rolls: usize,
68}
69
70impl LoggingConfiguration {
71    /// Returns a configuration that writes only to the console in human-readable format at INFO level.
72    ///
73    /// Used as a safe default when an application hasn't yet supplied an explicit configuration.
74    pub fn simple() -> Self {
75        Self {
76            log_level: LevelFilter::INFO.into(),
77            log_format_json: false,
78            log_format_rfc3339: false,
79            log_to_console: true,
80            log_to_syslog: false,
81            syslog_uri: String::new(),
82            syslog_rfc: false,
83            log_file: String::new(),
84            log_file_max_size: DEFAULT_LOG_FILE_MAX_SIZE,
85            log_file_max_rolls: DEFAULT_LOG_FILE_MAX_ROLLS,
86        }
87    }
88}
89
90#[cfg(test)]
91mod tests {
92    use super::*;
93
94    #[test]
95    fn simple_defaults_to_console_only_logging_with_syslog_disabled() {
96        let config = LoggingConfiguration::simple();
97
98        assert_eq!(config.log_level.as_targets().to_string(), "info");
99        assert!(!config.log_format_json);
100        assert!(!config.log_format_rfc3339);
101        assert!(config.log_to_console);
102        assert!(!config.log_to_syslog);
103        assert!(config.syslog_uri.is_empty());
104        assert!(!config.syslog_rfc);
105        assert!(config.log_file.is_empty());
106        assert_eq!(config.log_file_max_size, DEFAULT_LOG_FILE_MAX_SIZE);
107        assert_eq!(config.log_file_max_rolls, DEFAULT_LOG_FILE_MAX_ROLLS);
108    }
109
110    #[test]
111    fn log_level_try_from_rejects_empty_string() {
112        let error = match LogLevel::try_from(String::new()) {
113            Ok(_) => panic!("an empty log level must be rejected"),
114            Err(error) => error,
115        };
116        assert!(
117            error.to_string().contains("cannot be empty"),
118            "unexpected error message: {error}"
119        );
120    }
121
122    #[test]
123    fn log_level_try_from_parses_valid_directive() {
124        let log_level = LogLevel::try_from("saluki=debug".to_string()).expect("a valid directive should parse");
125        assert_eq!(log_level.as_targets().to_string(), "saluki=debug");
126    }
127}
128
129/// A parsed `tracing` log level filter.
130///
131/// Wraps [`Targets`] so it can be deserialized from a string (for example, `"info"`, `"saluki=trace,info"`). See
132/// [`parse_filter_directives`] for the accepted syntax.
133#[derive(Deserialize)]
134#[serde(try_from = "String")]
135pub struct LogLevel(Targets);
136
137impl LogLevel {
138    /// Returns the underlying `Targets` filter.
139    pub fn as_targets(&self) -> Targets {
140        self.0.clone()
141    }
142
143    /// Creates a `LogLevel` at the INFO level.
144    ///
145    /// This applies to all targets, with no prefix filtering whatsoever.
146    pub fn info() -> Self {
147        Self(Targets::new().with_default(Level::INFO))
148    }
149}
150
151impl From<LevelFilter> for LogLevel {
152    fn from(level: LevelFilter) -> Self {
153        Self(Targets::new().with_default(level))
154    }
155}
156
157impl TryFrom<String> for LogLevel {
158    type Error = GenericError;
159
160    fn try_from(value: String) -> Result<Self, Self::Error> {
161        if value.is_empty() {
162            return Err(generic_error!("Log level cannot be empty."));
163        }
164
165        parse_filter_directives(&value)
166            .map(Self)
167            .error_context("Failed to parse valid log level.")
168    }
169}
170
171impl fmt::Display for LogLevel {
172    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
173        self.0.fmt(f)
174    }
175}