1use 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#[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#[derive(Debug, Clone, Default)]
96pub struct OtelConfig {
97 pub enabled: bool,
99 pub service_name: Option<String>,
101 pub endpoint: Option<String>,
103 pub headers: HashMap<String, String>,
105}
106
107#[derive(Debug)]
108pub struct LoggingConfig {
109 pub level: LogLevel,
110 pub file_config: Option<FileLoggingConfig>,
111 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 pub file_prefix: Option<String>,
127 pub rotation: Option<LogRotation>,
129}
130
131#[derive(Debug, Default, Clone)]
132pub struct LogThrottlingConfig {
133 pub summary_emission_interval: Option<Duration>,
135 pub metrics_emission_interval: Option<Duration>,
137 pub excluded_fields: Option<Vec<String>>,
145 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 pub log_throttling_handle: TracingRateLimitLayer,
164}
165
166#[cfg(feature = "std")]
168struct LoggingSubscriberParts {
169 subscriber: Box<dyn Subscriber + Send + Sync + 'static>,
170 reload_handle: LogReloadHandle,
171 log_guards: (WorkerGuard, Option<WorkerGuard>), #[cfg(feature = "error_aggregation")]
173 errors_container: Arc<ErrorAggregationContainer>,
174 #[cfg(feature = "log_throttling")]
175 log_throttling_handle: TracingRateLimitLayer,
176}
177
178#[cfg(feature = "std")]
181fn build_logging_subscriber(config: LoggingConfig) -> eyre::Result<LoggingSubscriberParts> {
182 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()]; #[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 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 })) .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 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 let subscriber = registry().with(reloadable_global_filter);
290
291 let sinks = stdout_layer.and_then(file_layer);
293
294 #[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 let subscriber = subscriber.with(sinks);
304
305 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#[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#[cfg(feature = "std")]
377pub type GlobalLogReloadHandle = Handle<EnvFilter, Registry>;
378#[cfg(not(feature = "std"))]
379pub type GlobalLogReloadHandle = ();
380
381#[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 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
429pub 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); 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#[cfg(all(test, feature = "std"))]
489pub fn setup_logging_test(config: LoggingConfig) -> eyre::Result<LogSetupReturnTest> {
490 let parts = build_logging_subscriber(config)?;
491
492 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 #[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 info!("Test info message");
539 error!("Test error message");
540 }
541
542 #[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 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 let result = log_setup.reload_handle.set_log_level(LogLevel::Debug);
575 assert!(result.is_ok());
576
577 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 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 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 assert!(log_contents.contains("info_message_after_reload"));
603
604 assert!(
606 log_contents.contains("debug_message_after_reload"),
607 "Debug should appear after reload to DEBUG level"
608 );
609 }
610
611 #[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 #[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]
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()), ..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 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 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]
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 info!("info_before_reload");
736 debug!("debug_before_reload"); std::thread::sleep(std::time::Duration::from_millis(100));
739
740 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 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]
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 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}