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