1use 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#[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#[derive(Debug, Clone, Default)]
102pub struct OtelConfig {
103 pub enabled: bool,
105 pub service_name: Option<String>,
107 pub endpoint: Option<String>,
109 pub headers: HashMap<String, String>,
111}
112
113#[derive(Debug)]
114pub struct LoggingConfig {
115 pub level: LogLevel,
116 pub file_config: Option<FileLoggingConfig>,
117 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 pub file_prefix: Option<String>,
133 pub rotation: Option<LogRotation>,
135}
136
137#[derive(Debug, Default, Clone)]
138pub struct LogThrottlingConfig {
139 pub summary_emission_interval: Option<Duration>,
141 pub metrics_emission_interval: Option<Duration>,
143 pub excluded_fields: Option<Vec<String>>,
151 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 pub log_throttling_handle: TracingRateLimitLayer,
170}
171
172#[cfg(feature = "std")]
174struct LoggingSubscriberParts {
175 subscriber: Box<dyn Subscriber + Send + Sync + 'static>,
176 reload_handle: LogReloadHandle,
177 log_guards: (WorkerGuard, Option<WorkerGuard>), #[cfg(feature = "error_aggregation")]
179 errors_container: Arc<ErrorAggregationContainer>,
180 #[cfg(feature = "log_throttling")]
181 log_throttling_handle: TracingRateLimitLayer,
182}
183
184#[cfg(feature = "std")]
187fn build_logging_subscriber(config: LoggingConfig) -> eyre::Result<LoggingSubscriberParts> {
188 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()]; #[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 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 })) .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 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 let subscriber = registry().with(reloadable_global_filter);
296
297 let sinks = stdout_layer.and_then(file_layer);
299
300 #[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 let subscriber = subscriber.with(sinks);
310
311 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#[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#[cfg(feature = "std")]
383pub type GlobalLogReloadHandle = Handle<EnvFilter, Registry>;
384#[cfg(not(feature = "std"))]
385pub type GlobalLogReloadHandle = ();
386
387#[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 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
435pub 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); 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#[cfg(test)]
495pub fn setup_logging_test(config: LoggingConfig) -> eyre::Result<LogSetupReturnTest> {
496 let parts = build_logging_subscriber(config)?;
497
498 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 #[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 info!("Test info message");
545 error!("Test error message");
546 }
547
548 #[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 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 let result = log_setup.reload_handle.set_log_level(LogLevel::Debug);
581 assert!(result.is_ok());
582
583 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 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 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 assert!(log_contents.contains("info_message_after_reload"));
609
610 assert!(
612 log_contents.contains("debug_message_after_reload"),
613 "Debug should appear after reload to DEBUG level"
614 );
615 }
616
617 #[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 #[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]
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()), ..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 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 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]
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 info!("info_before_reload");
742 debug!("debug_before_reload"); std::thread::sleep(std::time::Duration::from_millis(100));
745
746 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 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]
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 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}