Skip to main content

endpoint_libs/libs/
log.rs

1//! Tracing-based logging setup with stdout and file logging
2//!
3//! # OpenTelemetry
4//! There is no OTLP export here any more. The exporter stack this crate used --
5//! `opentelemetry-otlp` and the SDK providers behind it -- was the last thing in the
6//! graph that pulled tokio in, and it did so for the protobuf *message types* rather
7//! than for a runtime: `http-proto` requires `opentelemetry-proto/gen-tonic-messages`,
8//! that feature is `["tonic", "tonic-prost", "prost"]`, and tonic 0.14 lists
9//! `tokio-stream` as a non-optional dependency, which in turn lists tokio. No transport
10//! or encoding choice on `opentelemetry-otlp` 0.31 avoids those types, so the only ways
11//! out were to hand-roll an OTLP encoder or to drop the exporter. Nothing in the fleet
12//! enabled the `otel` feature, so the exporter went.
13//!
14//! [`OtelConfig`] stays because several backends construct it inside a [`LoggingConfig`]
15//! literal and deleting it would break their builds for no gain. It is inert: setting
16//! `enabled: true` now warns at setup and forwards nothing.
17
18use alloc::boxed::Box;
19use alloc::string::String;
20use alloc::vec::Vec;
21use core::time::Duration;
22
23#[cfg(feature = "std")]
24use std::{collections::HashMap, path::PathBuf};
25#[cfg(not(feature = "std"))]
26use alloc::collections::BTreeMap as HashMap;
27#[cfg(all(not(feature = "std"), feature = "eko"))]
28use eko::path::PathBuf;
29#[cfg(all(not(feature = "std"), not(feature = "eko")))]
30type PathBuf = String;
31
32#[cfg(not(any(feature = "std", feature = "std-deps")))]
33use crate::eyre::{self, DefaultHandler, EyreHandler, bail};
34#[cfg(any(feature = "std", feature = "std-deps"))]
35use eyre::{self, DefaultHandler, EyreHandler, bail};
36
37#[cfg(feature = "std")]
38use chrono::SecondsFormat;
39#[cfg(feature = "std")]
40use tracing::Subscriber;
41#[cfg(feature = "std")]
42use tracing_appender::rolling::RollingFileAppender;
43#[cfg(feature = "std")]
44use tracing_subscriber::{
45    EnvFilter, Layer, Registry,
46    layer::SubscriberExt,
47    registry,
48    reload::{self, Handle},
49};
50
51#[cfg(feature = "log_throttling")]
52use tracing_throttle::TracingRateLimitLayer;
53
54#[cfg(feature = "error_aggregation")]
55use {crate::libs::log::error_aggregation::*, std::sync::Arc};
56
57#[deprecated(
58    since = "1.3.0",
59    note = "This code is not used in current projects and should probably not be used going forward"
60)]
61pub mod legacy;
62
63#[cfg(feature = "error_aggregation")]
64pub mod error_aggregation;
65pub mod level_filter;
66
67pub use level_filter::*;
68
69// Public re-export of Rotation so clients don't need to include tracing_appender just for log setup
70#[cfg(feature = "std")]
71pub use tracing_appender::rolling::Rotation as LogRotation;
72
73#[cfg(feature = "std")]
74pub use tracing_appender::non_blocking::WorkerGuard;
75
76#[cfg(not(feature = "std"))]
77#[derive(Debug, Clone, PartialEq, Eq)]
78pub enum LogRotation {
79    MINUTELY,
80    HOURLY,
81    DAILY,
82    NEVER,
83}
84
85#[cfg(not(feature = "std"))]
86pub use legacy::WorkerGuard;
87
88/// Configuration for OpenTelemetry integration.
89///
90/// Inert. It used to drive an OTLP exporter; that exporter is gone (see the module
91/// docs for why), and nothing reads these fields any more except the `enabled` flag,
92/// which [`setup_logging`] warns about so an operator who configured a collector is
93/// told to their face that nothing is being sent.
94///
95/// It is kept, rather than deleted with the exporter, because it lives in the `types`
96/// feature and four backends name it in a `LoggingConfig` struct literal. It carries no
97/// dependency of its own -- a bool, two `Option<String>`s and a map -- so keeping it
98/// costs nothing and removing it would be a source break with no compile-time benefit.
99/// It is also the seam to reattach an exporter to, if one ever comes back on a
100/// tokio-free transport.
101#[derive(Debug, Clone, Default)]
102pub struct OtelConfig {
103    /// Whether OTel log/trace forwarding was requested. Requesting it now only warns.
104    pub enabled: bool,
105    /// Service name that would identify this application to a collector.
106    pub service_name: Option<String>,
107    /// OTLP collector endpoint (e.g., "http://localhost:4318").
108    pub endpoint: Option<String>,
109    /// Additional headers that would be sent with OTLP requests (e.g., authentication).
110    pub headers: HashMap<String, String>,
111}
112
113#[derive(Debug)]
114pub struct LoggingConfig {
115    pub level: LogLevel,
116    pub file_config: Option<FileLoggingConfig>,
117    /// OpenTelemetry configuration. Accepted and ignored: OTLP export was removed, so
118    /// `enabled: true` forwards nothing and logs a warning at setup. The field stays so
119    /// existing `LoggingConfig` literals keep compiling. See [`OtelConfig`].
120    pub otel_config: OtelConfig,
121    #[cfg(feature = "error_aggregation")]
122    pub error_aggregation: ErrorAggregationConfig,
123    #[cfg(feature = "log_throttling")]
124    pub throttling_config: Option<LogThrottlingConfig>,
125}
126
127#[derive(Debug, Clone)]
128pub struct FileLoggingConfig {
129    pub path: PathBuf,
130    /// The name of the log file before the '.log', e.g. <file_prefix>.log will be the final log file.
131    /// Set to None for the current timestamp
132    pub file_prefix: Option<String>,
133    // Specifying None means that there will be one log file per program execution
134    pub rotation: Option<LogRotation>,
135}
136
137#[derive(Debug, Default, Clone)]
138pub struct LogThrottlingConfig {
139    /// How often to emit throttling summaries as WARN events, set to None to disable entirely
140    pub summary_emission_interval: Option<Duration>,
141    /// How often to throttling metrics as INFO events, set to None to disable entirely
142    pub metrics_emission_interval: Option<Duration>,
143    /// Fields to exclude from uniqueness checks, set to None to disable entirely.<br><br>
144    /// Example:
145    /// ```ignore
146    /// tracing::info!(user_id=1, "User joined");
147    /// tracing::info!(user_id=2, "User joined");  
148    ///```
149    /// If the `user_id` field is excluded, these will be treated as exactly the same log, so multiple users join messages could be throttled
150    pub excluded_fields: Option<Vec<String>>,
151    /// Targets to exempt from any throttling. This allows the caller to ensure that any high priority logs are always displayed.<br><br>
152    /// Example:
153    /// ```ignore
154    /// let exemptions = Some(vec!["nothrottle"]); // Assuming this is passed during config stage
155    ///
156    /// tracing::error!(target: "nothrottle", user_id=1, "User joined"); // Will never be throttled
157    /// tracing::error!(user_id=2, "User joined");  // Can possibly be throttled
158    /// ```
159    pub exemptions: Option<Vec<String>>,
160}
161
162pub struct LogSetupReturn {
163    pub reload_handle: LogReloadHandle,
164    pub log_guards: (WorkerGuard, Option<WorkerGuard>),
165    #[cfg(feature = "error_aggregation")]
166    pub errors_container: Arc<ErrorAggregationContainer>,
167    #[cfg(feature = "log_throttling")]
168    /// Call shutdown on this during graceful shutdown
169    pub log_throttling_handle: TracingRateLimitLayer,
170}
171
172/// Internal struct to hold the result of building the logging subscriber
173#[cfg(feature = "std")]
174struct LoggingSubscriberParts {
175    subscriber: Box<dyn Subscriber + Send + Sync + 'static>,
176    reload_handle: LogReloadHandle,
177    log_guards: (WorkerGuard, Option<WorkerGuard>), // Stdout and optional file log guards
178    #[cfg(feature = "error_aggregation")]
179    errors_container: Arc<ErrorAggregationContainer>,
180    #[cfg(feature = "log_throttling")]
181    log_throttling_handle: TracingRateLimitLayer,
182}
183
184/// Internal function that builds the logging subscriber without initializing it.
185/// Returns the subscriber along with reload handles and guards that need to be retained.
186#[cfg(feature = "std")]
187fn build_logging_subscriber(config: LoggingConfig) -> eyre::Result<LoggingSubscriberParts> {
188    // Build global env filter and wrap in reload::Layer for runtime reloading
189    let global_env_filter = build_env_filter(config.level)?;
190    let (reloadable_global_filter, global_reload_handle) = reload::Layer::new(global_env_filter);
191
192    let (non_blocking_stdout, stdout_guard) = tracing_appender::non_blocking(std::io::stdout());
193
194    let stdout_layer = tracing_subscriber::fmt::layer()
195        .with_thread_names(true)
196        .with_line_number(true)
197        .with_writer(non_blocking_stdout);
198
199    #[cfg(feature = "error_aggregation")]
200    let error_aggregation_config = config.error_aggregation.clone();
201
202    #[cfg(feature = "log_throttling")]
203    let throttling_config = config.throttling_config.clone().unwrap_or_default();
204
205    #[cfg(feature = "log_throttling")]
206    let mut exemptions = vec!["tracing_throttle::infrastructure::layer".to_string()]; // It seems like it tries to throttle its own logs
207    #[cfg(feature = "log_throttling")]
208    exemptions.extend(throttling_config.exemptions.unwrap_or_default());
209
210    #[cfg(feature = "log_throttling")]
211    let rate_limit_filter = TracingRateLimitLayer::builder()
212        .with_excluded_fields(throttling_config.excluded_fields.unwrap_or_default())
213        .with_exempt_targets(exemptions)
214        .with_active_emission(throttling_config.summary_emission_interval.is_some())
215        .with_summary_interval(
216            throttling_config
217                .summary_emission_interval
218                .unwrap_or(Duration::from_secs(5 * 60)),
219        )
220        .build()
221        .expect("Error building tracing rate limit layer");
222
223    #[cfg(feature = "log_throttling")]
224    if let Some(metrics_duration) = throttling_config.metrics_emission_interval {
225        let metrics = rate_limit_filter.metrics().clone();
226
227        // Periodic metrics reporting. Detached, as before: nothing collects this
228        // handle, and dropping a nagoya `JoinHandle` detaches rather than cancels.
229        nagoya::runtime::background().spawn(async move {
230            loop {
231                nagoya::sleep(metrics_duration).await;
232
233                let snapshot = metrics.snapshot();
234                tracing::info!(
235                    events_allowed = snapshot.events_allowed,
236                    events_suppressed = snapshot.events_suppressed,
237                    suppression_rate = format!("{:.1}%", snapshot.suppression_rate() * 100.0),
238                    "Rate limiting metrics"
239                );
240            }
241        });
242    }
243
244    #[cfg(feature = "log_throttling")]
245    let log_throttling_handle = rate_limit_filter.clone();
246
247    let (file_layer, file_guard) = match config.file_config {
248        None => (None, None),
249        Some(file_config) => {
250            let appender = RollingFileAppender::builder()
251                .rotation(file_config.rotation.unwrap_or(LogRotation::NEVER))
252                .filename_prefix(file_config.file_prefix.unwrap_or_else(|| {
253                    chrono::Utc::now().to_rfc3339_opts(SecondsFormat::Secs, true)
254                })) // Default filename prefix is a timestamp. RollingFileAppender requires a prefix if we are using a simple suffix like ".log"
255                .filename_suffix("log")
256                .build(file_config.path)?;
257
258            let (non_blocking_appender, guard) = tracing_appender::non_blocking(appender);
259
260            let base_layer = tracing_subscriber::fmt::layer()
261                .with_thread_names(true)
262                .with_line_number(true)
263                .with_ansi(false)
264                .with_writer(non_blocking_appender);
265
266            #[cfg(feature = "log_throttling")]
267            let file_layer = base_layer.with_filter(rate_limit_filter);
268
269            #[cfg(not(feature = "log_throttling"))]
270            let file_layer = base_layer;
271
272            (Some(file_layer), Some(guard))
273        }
274    };
275
276    let reload_handle = LogReloadHandle(global_reload_handle);
277
278    // There is no exporter to build any more, and no feature flag that brings one back.
279    // An operator who set `enabled: true` pointed this process at a collector and is
280    // entitled to find out that nothing arrives there, so the flag warns rather than
281    // being ignored. The warning fires once per `setup_logging` call, which is once per
282    // process in every consumer, and it names the config field so the fix is obvious.
283    if config.otel_config.enabled {
284        tracing::warn!(
285            target: "otel::setup",
286            endpoint = config.otel_config.endpoint.as_deref().unwrap_or("unset"),
287            "otel_config.enabled is true but OTLP export has been removed from endpoint-libs - \
288             no traces or logs will be forwarded to a collector"
289        );
290    }
291
292    // --- Subscriber Composition ---
293
294    // Start with Registry and Global Filter
295    let subscriber = registry().with(reloadable_global_filter);
296
297    // Compose the "Sink" layers (Stdout + File)
298    let sinks = stdout_layer.and_then(file_layer);
299
300    // Add Error Aggregation if enabled
301    #[cfg(feature = "error_aggregation")]
302    let (sinks, errors_container) = {
303        use crate::libs::log::error_aggregation::get_error_aggregation;
304        let (container, error_layer) = get_error_aggregation(error_aggregation_config);
305        (sinks.and_then(error_layer), container)
306    };
307
308    // Combine Subscriber with Sinks
309    let subscriber = subscriber.with(sinks);
310
311    // The box is still here with no OTel arm to choose against: `setup_logging` and
312    // `setup_logging_test` install the same concrete type, and the erasure is what lets
313    // the feature-gated layers above change the subscriber's type without changing this
314    // function's signature.
315    let subscriber: Box<dyn Subscriber + Send + Sync + 'static> = Box::new(subscriber);
316
317    Ok(LoggingSubscriberParts {
318        subscriber,
319        reload_handle,
320        log_guards: (stdout_guard, file_guard),
321        #[cfg(feature = "error_aggregation")]
322        errors_container,
323        #[cfg(feature = "log_throttling")]
324        log_throttling_handle,
325    })
326}
327
328/// Sets up a fully filtered tracing logging system with a global env filter applied at the registry level.
329/// This ensures all layers (stdout, file, etc.) only receive events that pass the global filter.
330///
331/// By default with the minimal config a stdout layer is setup with a custom env filter that filters according to the specified log level,
332/// as well as according to a list of hardcoded crates. See [build_env_filter] for hardcoded crate log filtering.
333/// Optionally, file logging can be configured with [FileLoggingConfig], which minimally will create a timestamp prefixed log file in the given
334/// path that does not rotate (one log file per program execution)
335///
336/// Extra configuration for file logging is:
337/// - Log file rotation. See [LogRotation] for possible options
338///
339/// Returns [LogSetupReturn], which is a composite struct containing objects that need to be retained by the client such as:
340/// - [LogReloadHandle], for setting a new global log level during runtime
341/// - [WorkerGuard], so that the non-blocking file writer can continue writing. This cannot be dropped and needs to be kept alive for the duration of the program execution
342/// - [ErrorAggregationContainer], if the [error_aggregation] feature is enabled. This object allows recent errors to be queried from the logging framework
343///
344/// `otel_config.enabled` is accepted and warned about; there is no OTel guard to return
345/// any more because there is no exporter to flush.
346#[cfg(feature = "std")]
347pub fn setup_logging(config: LoggingConfig) -> eyre::Result<LogSetupReturn> {
348    use tracing_subscriber::util::SubscriberInitExt;
349
350    let parts = build_logging_subscriber(config)?;
351
352    parts.subscriber.init();
353
354    Ok(LogSetupReturn {
355        reload_handle: parts.reload_handle,
356        log_guards: parts.log_guards,
357        #[cfg(feature = "error_aggregation")]
358        errors_container: parts.errors_container,
359        #[cfg(feature = "log_throttling")]
360        log_throttling_handle: parts.log_throttling_handle,
361    })
362}
363
364#[cfg(not(feature = "std"))]
365pub fn setup_logging(config: LoggingConfig) -> eyre::Result<LogSetupReturn> {
366    let _ = &config;
367    if config.otel_config.enabled {
368        tracing::warn!(
369            target: "otel::setup",
370            endpoint = config.otel_config.endpoint.as_deref().unwrap_or("unset"),
371            "otel_config.enabled is true but OTLP export has been removed from endpoint-libs - \
372             no traces or logs will be forwarded to a collector"
373        );
374    }
375    Ok(LogSetupReturn {
376        reload_handle: LogReloadHandle(()),
377        log_guards: (WorkerGuard, None),
378    })
379}
380
381/// Handle for reloading the global EnvFilter at runtime
382#[cfg(feature = "std")]
383pub type GlobalLogReloadHandle = Handle<EnvFilter, Registry>;
384#[cfg(not(feature = "std"))]
385pub type GlobalLogReloadHandle = ();
386
387/// Handle for reloading the global log level at runtime
388#[derive(Clone)]
389pub struct LogReloadHandle(GlobalLogReloadHandle);
390
391impl core::fmt::Debug for LogReloadHandle {
392    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
393        f.debug_struct("LogReloadHandle")
394            .field("inner", &"Handle<EnvFilter, Registry>")
395            .finish()
396    }
397}
398
399impl LogReloadHandle {
400    /// Sets a new global log level that applies to all layers (stdout, file, etc.)
401    /// Errors will be logged by this function and can be safely ignored, but are returned for display purposes
402    pub fn set_log_level(&self, level: LogLevel) -> eyre::Result<()> {
403        #[cfg(feature = "std")]
404        {
405            match build_env_filter(level) {
406                Ok(filter) => match self.0.modify(|env_filter| *env_filter = filter) {
407                    Ok(_) => Ok(()),
408                    Err(error) => {
409                        tracing::error!(
410                            ?error,
411                            "Error setting new global log filter. Ignoring reload attempt"
412                        );
413                        bail!("Error setting new global log filter: {error}. Ignoring reload attempt")
414                    }
415                },
416                Err(error) => {
417                    tracing::error!(
418                        ?error,
419                        "Error building new filter from given log level. Ignoring reload attempt"
420                    );
421                    bail!(
422                        "Error building new filter from given log level: {error}. Ignoring reload attempt"
423                    )
424                }
425            }
426        }
427        #[cfg(not(feature = "std"))]
428        {
429            let _ = level;
430            Ok(())
431        }
432    }
433}
434
435/// This is used to wrap the default EyreHandler but simply expose the [CustomEyreHandler::location] field via [CustomEyreHandler::get_location]
436/// This allows the code in [crate::libs::ws::internal_error_to_resp] to access the original caller location which is then stored in a [tracing::Field]
437/// for access within [error_aggregation::ErrorAggregationLayer::on_event] (see trait impl) so that the original caller can be recorded within the displayed target
438pub struct CustomEyreHandler {
439    default_handler: Box<dyn EyreHandler>,
440    location: Option<&'static core::panic::Location<'static>>,
441}
442
443impl CustomEyreHandler {
444    pub fn default_with_location_saving(
445        error: &(dyn core::error::Error + 'static),
446    ) -> Box<dyn EyreHandler> {
447        Box::new(Self {
448            default_handler: DefaultHandler::default_with(error),
449            location: None,
450        })
451    }
452
453    pub fn get_location(&self) -> &Option<&'static core::panic::Location<'static>> {
454        &self.location
455    }
456}
457
458impl EyreHandler for CustomEyreHandler {
459    fn display(
460        &self,
461        error: &(dyn core::error::Error + 'static),
462        f: &mut core::fmt::Formatter<'_>,
463    ) -> core::fmt::Result {
464        self.default_handler.display(error, f)
465    }
466
467    fn debug(
468        &self,
469        error: &(dyn core::error::Error + 'static),
470        f: &mut core::fmt::Formatter<'_>,
471    ) -> core::fmt::Result {
472        self.default_handler.debug(error, f)
473    }
474
475    fn track_caller(&mut self, location: &'static core::panic::Location<'static>) {
476        self.location = Some(location); // Store the location for access later
477        self.default_handler.track_caller(location);
478    }
479}
480
481#[cfg(test)]
482pub struct LogSetupReturnTest {
483    _guard: tracing::subscriber::DefaultGuard,
484    reload_handle: LogReloadHandle,
485    #[allow(dead_code)]
486    log_guards: (WorkerGuard, Option<WorkerGuard>),
487    #[cfg(feature = "error_aggregation")]
488    #[allow(dead_code)]
489    errors_container: Arc<ErrorAggregationContainer>,
490}
491
492/// Test-specific logging setup that uses thread-local scoped dispatcher instead of global
493/// This allows multiple tests to run without conflicting over the global subscriber
494#[cfg(test)]
495pub fn setup_logging_test(config: LoggingConfig) -> eyre::Result<LogSetupReturnTest> {
496    let parts = build_logging_subscriber(config)?;
497
498    // Use thread-local default instead of global
499    let guard = tracing::subscriber::set_default(parts.subscriber);
500
501    Ok(LogSetupReturnTest {
502        _guard: guard,
503        reload_handle: parts.reload_handle,
504        log_guards: parts.log_guards,
505        #[cfg(feature = "error_aggregation")]
506        errors_container: parts.errors_container,
507    })
508}
509
510#[cfg(test)]
511mod tests {
512    use super::*;
513    use std::fs;
514    use tracing::{debug, error, info};
515
516    #[cfg(feature = "error_aggregation")]
517    fn default_error_aggregation_config() -> ErrorAggregationConfig {
518        ErrorAggregationConfig {
519            limit: 100,
520            normalize: true,
521        }
522    }
523
524    /// Basic test that verifies logging setup succeeds and logs can be emitted
525    // These were `#[tokio::test]` only to have a runtime in scope; not one of
526    // them awaits anything, and the waits are `std::thread::sleep` for the
527    // non-blocking appender to drain. They are plain tests now.
528    #[test]
529    fn test_basic_logging_stdout() {
530        let config = LoggingConfig {
531            level: LogLevel::Info,
532            file_config: None,
533            otel_config: OtelConfig::default(),
534            #[cfg(feature = "error_aggregation")]
535            error_aggregation: default_error_aggregation_config(),
536            #[cfg(feature = "log_throttling")]
537            throttling_config: Some(LogThrottlingConfig::default()),
538        };
539
540        let _guard = setup_logging_test(config);
541        assert!(_guard.is_ok(), "Failed to setup logging");
542
543        // Emit some logs to verify the system works
544        info!("Test info message");
545        error!("Test error message");
546    }
547
548    /// Test file logging functionality including:
549    /// - Basic file logging
550    /// - Log level filtering (separate stdout vs file levels)
551    /// - Log level reloading at runtime
552    #[test]
553    fn test_file_logging_comprehensive() {
554        let temp_dir = tempfile::tempdir().unwrap();
555
556        let config = LoggingConfig {
557            level: LogLevel::Info,
558            file_config: Some(FileLoggingConfig {
559                path: temp_dir.path().to_path_buf(),
560                file_prefix: Some("test".to_string()),
561                rotation: None,
562            }),
563            otel_config: OtelConfig::default(),
564            #[cfg(feature = "error_aggregation")]
565            error_aggregation: default_error_aggregation_config(),
566            #[cfg(feature = "log_throttling")]
567            throttling_config: Some(LogThrottlingConfig::default()),
568        };
569
570        let log_setup = setup_logging_test(config).unwrap();
571
572        // Test 1: Basic logging and level filtering (before reload)
573        info!("info_message_before_reload");
574        debug!("debug_message_before_reload");
575        error!("error_message");
576
577        std::thread::sleep(std::time::Duration::from_millis(100));
578
579        // Test 2: Reload global log level to DEBUG
580        let result = log_setup.reload_handle.set_log_level(LogLevel::Debug);
581        assert!(result.is_ok());
582
583        // Test 3: Verify debug logs now appear after reload
584        info!("info_message_after_reload");
585        debug!("debug_message_after_reload");
586
587        std::thread::sleep(std::time::Duration::from_millis(100));
588        drop(log_setup);
589
590        std::thread::sleep(std::time::Duration::from_millis(100));
591
592        // Verify file was created and contains expected logs
593        let log_files: Vec<_> = fs::read_dir(temp_dir.path()).unwrap().collect();
594        assert_eq!(log_files.len(), 1, "Expected exactly one log file");
595
596        let log_file = log_files[0].as_ref().unwrap();
597        let log_contents = fs::read_to_string(log_file.path()).unwrap();
598
599        // Verify messages before reload
600        assert!(log_contents.contains("info_message_before_reload"));
601        assert!(
602            !log_contents.contains("debug_message_before_reload"),
603            "Debug should not appear before reload"
604        );
605        assert!(log_contents.contains("error_message"));
606
607        // Verify messages after reload
608        assert!(log_contents.contains("info_message_after_reload"));
609
610        // Global log level reload applies to all layers including file
611        assert!(
612            log_contents.contains("debug_message_after_reload"),
613            "Debug should appear after reload to DEBUG level"
614        );
615    }
616
617    // === OTel config tests ===
618    //
619    // OTLP export is gone; `OtelConfig` remains as an inert config struct so
620    // the backends that build a `LoggingConfig` literal keep compiling. What
621    // is worth asserting is therefore no longer that an exporter came up, but
622    // that asking for one is accepted, warned about, and harmless.
623
624    /// A config with `enabled: true` must not fail setup, and must not take
625    /// the rest of the subscriber down with it.
626    ///
627    /// This replaces `test_otel_disabled_returns_none_guards` and
628    /// `test_otel_graceful_degradation_unreachable_endpoint`, which asserted
629    /// on `LogSetupReturn::otel_guards`. That field went with the exporter.
630    /// The endpoint is still the unreachable one those tests used, because the
631    /// property that matters is unchanged: nothing here may try to reach it at
632    /// setup time.
633    #[test]
634    fn enabling_otel_is_accepted_and_changes_nothing() {
635        let config = LoggingConfig {
636            level: LogLevel::Info,
637            file_config: None,
638            otel_config: OtelConfig {
639                enabled: true,
640                endpoint: Some("http://nonexistent.invalid:4317".to_string()),
641                ..OtelConfig::default()
642            },
643            #[cfg(feature = "error_aggregation")]
644            error_aggregation: default_error_aggregation_config(),
645            #[cfg(feature = "log_throttling")]
646            throttling_config: None,
647        };
648
649        let result = setup_logging_test(config);
650        assert!(
651            result.is_ok(),
652            "an otel_config asking for export must not fail setup"
653        );
654    }
655
656    /// The default config asks for nothing and is the common case.
657    #[test]
658    fn a_default_otel_config_sets_up_cleanly() {
659        let config = LoggingConfig {
660            level: LogLevel::Info,
661            file_config: None,
662            otel_config: OtelConfig::default(),
663            #[cfg(feature = "error_aggregation")]
664            error_aggregation: default_error_aggregation_config(),
665            #[cfg(feature = "log_throttling")]
666            throttling_config: None,
667        };
668
669        assert!(setup_logging_test(config).is_ok());
670    }
671
672    /// Test that file logging works alongside OTel enabled (but with invalid endpoint)
673    /// This verifies that the layer composition doesn't break when OTel is attempted
674    #[test]
675    fn test_file_logging_with_otel_attempted() {
676        let temp_dir = tempfile::tempdir().unwrap();
677
678        let config = LoggingConfig {
679            level: LogLevel::Info,
680            file_config: Some(FileLoggingConfig {
681                path: temp_dir.path().to_path_buf(),
682                file_prefix: Some("otel_test".to_string()),
683                rotation: None,
684            }),
685            otel_config: OtelConfig {
686                enabled: true,
687                endpoint: Some("http://localhost:4317".to_string()), // Not running
688                ..OtelConfig::default()
689            },
690            #[cfg(feature = "error_aggregation")]
691            error_aggregation: default_error_aggregation_config(),
692            #[cfg(feature = "log_throttling")]
693            throttling_config: None,
694        };
695
696        let log_setup = setup_logging_test(config).unwrap();
697
698        // Emit logs - these should go to file regardless of OTel status
699        info!("file_log_with_otel_attempted");
700        error!("error_log_with_otel_attempted");
701
702        std::thread::sleep(std::time::Duration::from_millis(100));
703        drop(log_setup);
704        std::thread::sleep(std::time::Duration::from_millis(100));
705
706        // Verify file was created and contains logs
707        let log_files: Vec<_> = fs::read_dir(temp_dir.path()).unwrap().collect();
708        assert_eq!(log_files.len(), 1, "Expected exactly one log file");
709
710        let log_contents = fs::read_to_string(log_files[0].as_ref().unwrap().path()).unwrap();
711        assert!(log_contents.contains("file_log_with_otel_attempted"));
712        assert!(log_contents.contains("error_log_with_otel_attempted"));
713    }
714
715    /// Test that log level reload works correctly when OTel is enabled
716    #[test]
717    fn test_log_level_reload_with_otel_enabled() {
718        let temp_dir = tempfile::tempdir().unwrap();
719
720        let config = LoggingConfig {
721            level: LogLevel::Info,
722            file_config: Some(FileLoggingConfig {
723                path: temp_dir.path().to_path_buf(),
724                file_prefix: Some("reload_test".to_string()),
725                rotation: None,
726            }),
727            otel_config: OtelConfig {
728                enabled: true,
729                endpoint: Some("http://localhost:4317".to_string()),
730                ..OtelConfig::default()
731            },
732            #[cfg(feature = "error_aggregation")]
733            error_aggregation: default_error_aggregation_config(),
734            #[cfg(feature = "log_throttling")]
735            throttling_config: None,
736        };
737
738        let log_setup = setup_logging_test(config).unwrap();
739
740        // Log at INFO level (should appear)
741        info!("info_before_reload");
742        debug!("debug_before_reload"); // Should NOT appear
743
744        std::thread::sleep(std::time::Duration::from_millis(100));
745
746        // Reload to DEBUG
747        let result = log_setup.reload_handle.set_log_level(LogLevel::Debug);
748        assert!(
749            result.is_ok(),
750            "Log level reload should succeed with OTel enabled"
751        );
752
753        // Log at DEBUG level (should now appear)
754        info!("info_after_reload");
755        debug!("debug_after_reload");
756
757        std::thread::sleep(std::time::Duration::from_millis(100));
758        drop(log_setup);
759        std::thread::sleep(std::time::Duration::from_millis(100));
760
761        let log_files: Vec<_> = fs::read_dir(temp_dir.path()).unwrap().collect();
762        let log_contents = fs::read_to_string(log_files[0].as_ref().unwrap().path()).unwrap();
763
764        assert!(log_contents.contains("info_before_reload"));
765        assert!(
766            !log_contents.contains("debug_before_reload"),
767            "Debug should not appear before reload"
768        );
769        assert!(log_contents.contains("info_after_reload"));
770        assert!(
771            log_contents.contains("debug_after_reload"),
772            "Debug should appear after reload"
773        );
774    }
775
776    /// Test that OTel config fields are correctly structured
777    #[test]
778    fn test_otel_config_fields() {
779        use std::collections::HashMap;
780
781        let config = OtelConfig {
782            enabled: true,
783            service_name: Some("test-service".to_string()),
784            endpoint: Some("http://collector:4317".to_string()),
785            headers: {
786                let mut h = HashMap::new();
787                h.insert("x-api-key".to_string(), "secret-key".to_string());
788                h
789            },
790        };
791
792        assert!(config.enabled);
793        assert_eq!(config.service_name, Some("test-service".to_string()));
794        assert_eq!(config.endpoint, Some("http://collector:4317".to_string()));
795        assert_eq!(
796            config.headers.get("x-api-key"),
797            Some(&"secret-key".to_string())
798        );
799
800        // Default config should be disabled
801        let default_config = OtelConfig::default();
802        assert!(!default_config.enabled);
803        assert!(default_config.service_name.is_none());
804        assert!(default_config.endpoint.is_none());
805        assert!(default_config.headers.is_empty());
806    }
807}