Skip to main content

phoenix_logging/
lib.rs

1//! Structured application logging with safe, explicit defaults.
2
3use tracing::Subscriber;
4use tracing_subscriber::{EnvFilter, Registry, fmt, layer::SubscriberExt, util::SubscriberInitExt};
5
6/// Output format used by the Phoenix tracing subscriber.
7#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
8pub enum LogFormat {
9    /// Human-readable, compact output for local development.
10    #[default]
11    Compact,
12    /// Newline-delimited JSON suitable for production log collectors.
13    Json,
14}
15
16/// Builder for process-wide Phoenix logging.
17#[derive(Clone, Debug)]
18pub struct Logging {
19    format: LogFormat,
20    filter: String,
21    ansi: bool,
22    target: bool,
23}
24
25impl Default for Logging {
26    fn default() -> Self {
27        Self {
28            format: LogFormat::Compact,
29            filter: "info,hyper=warn".to_owned(),
30            ansi: true,
31            target: false,
32        }
33    }
34}
35
36impl Logging {
37    #[must_use]
38    pub fn new() -> Self {
39        Self::default()
40    }
41
42    #[must_use]
43    pub const fn format(mut self, format: LogFormat) -> Self {
44        self.format = format;
45        self
46    }
47
48    /// Set the fallback filter used when the configured environment variable is absent.
49    #[must_use]
50    pub fn filter(mut self, filter: impl Into<String>) -> Self {
51        self.filter = filter.into();
52        self
53    }
54
55    #[must_use]
56    pub const fn ansi(mut self, enabled: bool) -> Self {
57        self.ansi = enabled;
58        self
59    }
60
61    #[must_use]
62    pub const fn target(mut self, enabled: bool) -> Self {
63        self.target = enabled;
64        self
65    }
66
67    /// Install the subscriber using `PHOENIX_LOG`, falling back to this builder's filter.
68    ///
69    /// # Errors
70    ///
71    /// Returns an error for an invalid filter or when another global subscriber is installed.
72    pub fn init(self) -> Result<LoggingGuard, LoggingError> {
73        self.init_with_env("PHOENIX_LOG")
74    }
75
76    /// Install the subscriber using a custom environment variable name.
77    ///
78    /// # Errors
79    ///
80    /// Returns an error for an invalid filter or when another global subscriber is installed.
81    pub fn init_with_env(self, variable: &str) -> Result<LoggingGuard, LoggingError> {
82        let filter = EnvFilter::try_from_env(variable)
83            .or_else(|_| EnvFilter::try_new(&self.filter))
84            .map_err(LoggingError::Filter)?;
85        match self.format {
86            LogFormat::Compact => install(
87                Registry::default().with(filter).with(
88                    fmt::layer()
89                        .compact()
90                        .with_ansi(self.ansi)
91                        .with_target(self.target),
92                ),
93            ),
94            LogFormat::Json => install(
95                Registry::default().with(filter).with(
96                    fmt::layer()
97                        .json()
98                        .with_ansi(false)
99                        .with_target(self.target),
100                ),
101            ),
102        }
103    }
104}
105
106fn install<S>(subscriber: S) -> Result<LoggingGuard, LoggingError>
107where
108    S: Subscriber + Send + Sync,
109{
110    subscriber.try_init().map_err(LoggingError::Install)?;
111    Ok(LoggingGuard { _private: () })
112}
113
114/// Proof that Phoenix installed the process-wide logging subscriber.
115#[derive(Debug)]
116pub struct LoggingGuard {
117    _private: (),
118}
119
120#[derive(Debug)]
121pub enum LoggingError {
122    Filter(tracing_subscriber::filter::ParseError),
123    Install(tracing_subscriber::util::TryInitError),
124}
125
126impl std::fmt::Display for LoggingError {
127    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
128        match self {
129            Self::Filter(error) => write!(formatter, "invalid logging filter: {error}"),
130            Self::Install(error) => write!(formatter, "logging is already initialized: {error}"),
131        }
132    }
133}
134
135impl std::error::Error for LoggingError {
136    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
137        match self {
138            Self::Filter(error) => Some(error),
139            Self::Install(error) => Some(error),
140        }
141    }
142}
143
144#[cfg(test)]
145mod tests {
146    use super::*;
147
148    #[test]
149    fn defaults_are_safe_and_invalid_fallback_filters_fail() {
150        let logging = Logging::new();
151        assert_eq!(logging.format, LogFormat::Compact);
152        assert_eq!(logging.filter, "info,hyper=warn");
153
154        let error = Logging::new()
155            .filter("[invalid")
156            .init_with_env("PHOENIX_TEST_LOG_NOT_SET")
157            .expect_err("invalid filter must fail");
158        assert!(matches!(error, LoggingError::Filter(_)));
159    }
160}