logger.rs 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2025 Dyne.org foundation
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU Affero General Public License as
  7. * published by the Free Software Foundation, either version 3 of the
  8. * License, or (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU Affero General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU Affero General Public License
  16. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  17. */
  18. use tracing_appender::non_blocking::WorkerGuard;
  19. use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt, Layer, Registry};
  20. #[cfg(feature = "enable-filelog")]
  21. use {
  22. file_rotate::{compression::Compression, suffix::AppendCount, ContentLimit, FileRotate},
  23. std::path::PathBuf,
  24. };
  25. #[cfg(target_os = "android")]
  26. use tracing_subscriber::filter::{LevelFilter, Targets};
  27. #[cfg(any(not(target_os = "android"), feature = "enable-filelog"))]
  28. use {
  29. darkfi::util::logger::{EventFormatter, Level, TargetFilter},
  30. tracing_subscriber::fmt::format::FmtSpan,
  31. };
  32. // Measured in bytes
  33. #[cfg(feature = "enable-filelog")]
  34. const LOGFILE_MAXSIZE: usize = 5_000_000;
  35. static MUTED_TARGETS: &[&'static str] = &[
  36. "sled",
  37. "rustls",
  38. "async_io",
  39. "polling",
  40. "net::channel",
  41. "net::message_publisher",
  42. "net::hosts",
  43. "net::protocol",
  44. "net::session",
  45. "net::outbound_session",
  46. "net::tcp",
  47. "net::p2p::seed",
  48. "net::refinery::handshake_node()",
  49. "system::publisher",
  50. "event_graph::dag_sync()",
  51. "event_graph::dag_insert()",
  52. "event_graph::protocol",
  53. ];
  54. #[cfg(not(target_os = "android"))]
  55. static ALLOW_TRACE: &[&'static str] = &["ui", "app", "gfx"];
  56. #[cfg(all(target_os = "android", feature = "enable-filelog"))]
  57. fn logfile_path() -> PathBuf {
  58. use crate::android::get_external_storage_path;
  59. get_external_storage_path().join("darkfi-app.log")
  60. }
  61. #[cfg(all(not(target_os = "android"), feature = "enable-filelog"))]
  62. fn logfile_path() -> PathBuf {
  63. dirs::cache_dir().unwrap().join("darkfi/darkfi-app.log")
  64. }
  65. pub fn setup_logging() -> Option<WorkerGuard> {
  66. let mut layers: Vec<(Box<dyn Layer<Registry> + Send + Sync>, Option<WorkerGuard>)> = vec![];
  67. #[cfg(feature = "enable-filelog")]
  68. {
  69. let (non_blocking_file_rotate, guard) = tracing_appender::non_blocking(FileRotate::new(
  70. logfile_path(),
  71. AppendCount::new(0),
  72. ContentLimit::BytesSurpassed(LOGFILE_MAXSIZE),
  73. Compression::None,
  74. #[cfg(unix)]
  75. None,
  76. ));
  77. let file_layer = tracing_subscriber::fmt::Layer::new()
  78. .event_format(EventFormatter::new(false, true))
  79. .fmt_fields(tracing_subscriber::fmt::format::debug_fn(
  80. darkfi::util::logger::file_field_formatter,
  81. ))
  82. .with_writer(non_blocking_file_rotate)
  83. .with_filter(
  84. TargetFilter::default()
  85. .ignore_targets(["sled", "rustls", "async_io", "polling"])
  86. .default_level(Level::Trace),
  87. );
  88. layers.push((file_layer.boxed(), Some(guard)));
  89. }
  90. #[cfg(target_os = "android")]
  91. {
  92. let logcat_layer =
  93. tracing_android::layer("darkfi").expect("tracing_android layer").with_filter(
  94. Targets::new()
  95. .with_targets(
  96. crate::logger::MUTED_TARGETS.iter().map(|&t| (t, LevelFilter::OFF)),
  97. )
  98. .with_default(LevelFilter::TRACE),
  99. );
  100. layers.push((logcat_layer.boxed(), None));
  101. }
  102. #[cfg(not(target_os = "android"))]
  103. {
  104. let terminal_layer = tracing_subscriber::fmt::Layer::new()
  105. .with_span_events(FmtSpan::ENTER | FmtSpan::CLOSE)
  106. .event_format(EventFormatter::new(true, true))
  107. .fmt_fields(tracing_subscriber::fmt::format::debug_fn(
  108. darkfi::util::logger::terminal_field_formatter,
  109. ))
  110. .with_writer(std::io::stdout)
  111. .with_filter(
  112. TargetFilter::default()
  113. .targets_level(ALLOW_TRACE, Level::Trace)
  114. .targets_level(MUTED_TARGETS, Level::Info)
  115. .default_level(Level::Debug),
  116. );
  117. layers.push((terminal_layer.boxed(), None));
  118. }
  119. let file_logging_guard = layers.iter_mut().find_map(|l| l.1.take());
  120. Registry::default()
  121. .with(layers.into_iter().map(|l| l.0).collect::<Vec<_>>())
  122. .try_init()
  123. .expect("logger");
  124. file_logging_guard
  125. }