Skip to main content

saluki_app/logging/
mod.rs

1//! Logging.
2
3// TODO: `AgentLikeFieldVisitor` currently allocates a `String` to hold the message field when it finds it. This is
4// suboptimal because it means we allocate a string literally every time we log a message. Logging is rare, but it's
5// just a recipe for small, unnecessary allocations over time... and makes it that much more inefficient to enable
6// debug/trace-level logging in production.
7//
8// We might consider _something_ like a string pool in the future, but we can defer that until we have a better idea of
9// what the potential impact is in practice.
10
11use std::io::Write;
12
13use saluki_common::logging::RollingFileWriter;
14use saluki_core::runtime::Supervisor;
15use saluki_error::{generic_error, ErrorContext as _, GenericError};
16use tracing_appender::non_blocking::{NonBlocking, NonBlockingBuilder, WorkerGuard};
17use tracing_subscriber::{layer::SubscriberExt as _, reload, util::SubscriberInitExt as _, Layer, Registry};
18
19mod api;
20pub use self::api::{DynamicLogLevelWorker, LoggingAPIHandler, LoggingOverrideController, LoggingOverrideWorker};
21
22mod config;
23pub use self::config::{LogLevel, LoggingConfiguration};
24
25mod layer;
26use self::layer::{build_formatting_layer, build_syslog_formatting_layer};
27
28mod panic;
29use self::panic::install_panic_hook;
30
31mod syslog;
32use self::syslog::SyslogWriter;
33
34// Number of buffered lines in each non-blocking log writer.
35//
36// This directly influences the idle memory usage since each logging backend (console, file, etc) will have a bounded
37// channel that can hold this many elements, and each element is roughly 32 bytes, so 1,000 elements/lines consumes a
38// minimum of ~32KB, etc.
39const NB_LOG_WRITER_BUFFER_SIZE: usize = 4096;
40
41type OutputStack = Vec<Box<dyn Layer<Registry> + Send + Sync>>;
42
43/// A handle to the dynamic logging subsystem.
44///
45/// Held by [`BootstrapGuard`][crate::bootstrap::BootstrapGuard] for the lifetime of the application. Owns the
46/// worker guards (which flush buffered output on drop), and exposes [`reload`][Self::reload] for swapping the
47/// entire logging configuration plus [`controller`][Self::controller] for driving runtime filter changes through
48/// the override worker.
49pub struct LoggingGuard {
50    worker_guards: Vec<WorkerGuard>,
51    stack_handle: reload::Handle<OutputStack, Registry>,
52    controller: LoggingOverrideController,
53}
54
55impl LoggingGuard {
56    /// Reloads the logging subsystem from the given configuration.
57    ///
58    /// Rebuilds the output layer stack from `config` and routes the new level filter through the override worker
59    /// as the new base filter, so an active override is preserved (the new base will take effect once the override
60    /// expires). Worker guards for the previous outputs are dropped after the swap, which flushes any buffered log
61    /// lines to their original destinations.
62    ///
63    /// This is the right entry point when the entire logging configuration may have changed (for example, outputs,
64    /// format, level). For runtime base-filter changes only -- such as following a `log_level` config update --
65    /// use [`controller`][Self::controller] and call
66    /// [`update_base`][LoggingOverrideController::update_base] directly.
67    ///
68    /// # Errors
69    ///
70    /// Returns an error if the new output layers can't be constructed (for example, the configured syslog URI is
71    /// invalid) or if the override worker is no longer running.
72    pub async fn reload(&mut self, config: LoggingConfiguration) -> Result<(), GenericError> {
73        let (new_stack, new_guards) = build_output_stack(&config)?;
74        let new_filter = config.log_level.as_targets();
75
76        self.stack_handle
77            .reload(new_stack)
78            .map_err(|e| generic_error!("Failed to swap logging output stack: {}", e))?;
79        self.controller.update_base(new_filter).await?;
80
81        // Drop the old worker guards _after_ the swap so any buffered lines are flushed to their original destinations
82        // before the worker threads exit.
83        let _old_guards = std::mem::replace(&mut self.worker_guards, new_guards);
84
85        Ok(())
86    }
87
88    /// Returns a logging override controller that can be used to change the default filter directives.
89    pub fn controller(&self) -> LoggingOverrideController {
90        self.controller.clone()
91    }
92}
93
94/// Initializes the logging subsystem for `tracing` with the ability to dynamically update the log filtering directives
95/// at runtime.
96///
97/// Returns a [`LoggingGuard`] which must be held until the application is about to shutdown, plus a [`Supervisor`]
98/// holding the subsystem's background workers. The caller must arrange for that supervisor to run -- typically by
99/// adding it to a parent supervisor -- or override requests are accepted but never applied.
100///
101/// # Errors
102///
103/// If the logging subsystem was already initialized, or its supervisor can't be constructed, an error will be
104/// returned.
105pub(crate) async fn initialize_logging(
106    config: LoggingConfiguration,
107) -> Result<(LoggingGuard, Supervisor), GenericError> {
108    // Build the initial output stack from the supplied configuration. This is later swappable via
109    // `BootstrapGuard::reload_logging` once the Datadog Agent provides authoritative configuration.
110    let (output_stack, worker_guards) = build_output_stack(&config)?;
111    let (output_layer, stack_handle) = reload::Layer::new(output_stack);
112
113    // Set up our log level filtering and dynamic filter layer.
114    let (filter_layer, filter_handle) = reload::Layer::new(config.log_level.as_targets());
115
116    // The override worker owns the canonical base filter -- the directives the system restores to after an override
117    // expires or is reset. It seeds the base from the reload handle on startup and is updated via the controller,
118    // both by `LoggingGuard::reload` once the Agent's configuration is applied and by any other caller (for example, a
119    // runtime `log_level` watcher) wired up via [`LoggingGuard::controller`].
120    let (override_worker, controller) = LoggingOverrideWorker::new(filter_handle);
121
122    tracing_subscriber::registry()
123        .with(output_layer.with_filter(filter_layer))
124        .try_init()?;
125
126    // Log panics through the subscriber we just installed, so they reach the configured outputs and not only standard
127    // error. `try_init` fails on a second call, so the hook is installed at most once.
128    install_panic_hook();
129
130    // The override worker also asserts the privileged API routes for runtime filter control, so nothing driven
131    // through those routes takes effect until this supervisor is running.
132    let mut supervisor = Supervisor::new("logging").error_context("Failed to construct logging supervisor.")?;
133    supervisor.add_worker(override_worker);
134
135    Ok((
136        LoggingGuard {
137            worker_guards,
138            stack_handle,
139            controller,
140        },
141        supervisor,
142    ))
143}
144
145fn build_output_stack(config: &LoggingConfiguration) -> Result<(OutputStack, Vec<WorkerGuard>), GenericError> {
146    let mut layers: OutputStack = Vec::new();
147    let mut guards = Vec::new();
148
149    if config.log_to_console {
150        let (nb_stdout, guard) = writer_to_nonblocking("console", std::io::stdout());
151        guards.push(guard);
152        layers.push(build_formatting_layer(config, nb_stdout));
153    }
154
155    if !config.log_file.is_empty() {
156        // The file is opened on the first write, so an unusable path doesn't stop logging from starting.
157        let writer = RollingFileWriter::new(
158            &config.log_file,
159            config.log_file_max_size.as_u64(),
160            config.log_file_max_rolls,
161        );
162
163        let (nb_appender, guard) = writer_to_nonblocking("file", writer);
164        guards.push(guard);
165        layers.push(build_formatting_layer(config, nb_appender));
166    }
167
168    if config.log_to_syslog {
169        let syslog_writer = SyslogWriter::from_uri(&config.syslog_uri)
170            .map_err(|e| generic_error!("Failed to build syslog log writer: {}", e))?;
171        // Keep syslog on the same lossy non-blocking path as console/file so logging never
172        // backpressures ADP.
173        let (nb_syslog, guard) = writer_to_nonblocking("syslog", syslog_writer);
174        guards.push(guard);
175        layers.push(build_syslog_formatting_layer(config, nb_syslog));
176    }
177
178    Ok((layers, guards))
179}
180
181fn writer_to_nonblocking<W>(writer_name: &'static str, writer: W) -> (NonBlocking, WorkerGuard)
182where
183    W: Write + Send + 'static,
184{
185    let thread_name = format!("log-writer-{}", writer_name);
186    NonBlockingBuilder::default()
187        .thread_name(&thread_name)
188        .buffered_lines_limit(NB_LOG_WRITER_BUFFER_SIZE)
189        .lossy(true)
190        .finish(writer)
191}
192
193#[cfg(test)]
194mod tests {
195    use super::*;
196
197    const TEST_SYSLOG_URI: &str = "udp://127.0.0.1:9";
198
199    #[test]
200    fn output_stack_skips_syslog_when_disabled() {
201        let config = logging_config_without_outputs();
202
203        let (layers, guards) = build_output_stack(&config).expect("build output stack");
204
205        assert_eq!(layers.len(), 0);
206        assert_eq!(guards.len(), 0);
207    }
208
209    #[test]
210    fn output_stack_adds_syslog_layer_and_guard_when_enabled() {
211        let config = logging_config_with_syslog(TEST_SYSLOG_URI);
212
213        let (layers, guards) = build_output_stack(&config).expect("build output stack with syslog");
214
215        assert_eq!(layers.len(), 1);
216        assert_eq!(guards.len(), 1);
217    }
218
219    #[test]
220    fn output_stack_fails_when_syslog_uri_is_invalid() {
221        let config = logging_config_with_syslog("http://127.0.0.1:514");
222
223        let error = match build_output_stack(&config) {
224            Ok(_) => panic!("invalid syslog URI should fail output stack build"),
225            Err(error) => error,
226        };
227
228        let error = error.to_string();
229        assert!(error.contains("Failed to build syslog log writer"));
230        assert!(error.contains("Unsupported syslog URI scheme 'http'"));
231    }
232
233    #[tokio::test]
234    async fn reload_can_enable_change_disable_syslog_and_preserves_previous_stack_on_invalid_config() {
235        use saluki_core::runtime::test_util::TestSupervisor;
236
237        let config = logging_config_without_outputs();
238        let (output_stack, worker_guards) = build_output_stack(&config).expect("build initial output stack");
239        let (output_layer, stack_handle) = reload::Layer::new(output_stack);
240        let (filter_layer, filter_handle) = reload::Layer::new(config.log_level.as_targets());
241        let (override_worker, controller) = LoggingOverrideWorker::new(filter_handle);
242        let mut guard = LoggingGuard {
243            worker_guards,
244            stack_handle,
245            controller,
246        };
247        let _keep_layers_alive = (output_layer, filter_layer);
248
249        // Run the override worker inside a Supervisor so it has the dataspace context required for
250        // its route assertion. The supervisor's shutdown signal drives the worker to exit cleanly.
251        let supervisor = TestSupervisor::start_with("test-logging-override", |supervisor| {
252            supervisor.add_worker(override_worker);
253        })
254        .await;
255
256        guard
257            .reload(logging_config_with_syslog(TEST_SYSLOG_URI))
258            .await
259            .expect("reload should enable syslog");
260        assert_eq!(guard.worker_guards.len(), 1);
261
262        guard
263            .reload(logging_config_with_syslog("udp://127.0.0.1:10"))
264            .await
265            .expect("reload should change syslog URI");
266        assert_eq!(guard.worker_guards.len(), 1);
267
268        guard
269            .reload(logging_config_without_outputs())
270            .await
271            .expect("reload should disable syslog");
272        assert_eq!(guard.worker_guards.len(), 0);
273
274        guard
275            .reload(logging_config_with_syslog(TEST_SYSLOG_URI))
276            .await
277            .expect("reload should re-enable syslog");
278        assert_eq!(guard.worker_guards.len(), 1);
279
280        let error = guard
281            .reload(logging_config_with_syslog("http://127.0.0.1:514"))
282            .await
283            .expect_err("invalid syslog URI should fail reload");
284        assert!(error.to_string().contains("Failed to build syslog log writer"));
285        assert_eq!(guard.worker_guards.len(), 1);
286
287        // Trigger supervisor shutdown so the worker exits via its shutdown branch rather than via
288        // the channel-close path (which would prompt a restart attempt by the supervisor).
289        supervisor.shutdown().await.expect("supervisor should exit cleanly");
290        drop(guard);
291    }
292
293    fn logging_config_without_outputs() -> LoggingConfiguration {
294        let mut config = LoggingConfiguration::simple();
295        config.log_to_console = false;
296        config.log_file.clear();
297        config.log_to_syslog = false;
298        config.syslog_uri.clear();
299        config
300    }
301
302    fn logging_config_with_syslog(uri: &str) -> LoggingConfiguration {
303        let mut config = logging_config_without_outputs();
304        config.log_to_syslog = true;
305        config.syslog_uri = uri.to_string();
306        config
307    }
308}