logger.rs 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2026 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. std::sync::OnceLock,
  25. };
  26. #[cfg(target_os = "android")]
  27. use tracing_subscriber::filter::{LevelFilter, Targets};
  28. #[cfg(any(not(target_os = "android"), feature = "enable-filelog"))]
  29. use darkfi::util::logger::{EventFormatter, Level, TargetFilter};
  30. // Measured in bytes
  31. #[cfg(feature = "enable-filelog")]
  32. const LOGFILE_MAXSIZE: usize = 5_000_000;
  33. static MUTED_TARGETS: &[&'static str] = &[
  34. "sled",
  35. "rustls",
  36. "async_io",
  37. "polling",
  38. "net::channel",
  39. "net::message_publisher",
  40. "net::hosts",
  41. "net::protocol",
  42. "net::session",
  43. "net::outbound_session",
  44. "net::tcp",
  45. "net::p2p::seed",
  46. "net::refinery::handshake_node()",
  47. "system::publisher",
  48. "event_graph::dag_sync()",
  49. "event_graph::dag_insert()",
  50. "event_graph::protocol",
  51. "turso_core",
  52. "turso_sqlite",
  53. "walletdb",
  54. "rpc::client",
  55. // Bridged `log` crate records (pulseaudio protocol trace spam)
  56. "log",
  57. "pulseaudio",
  58. ];
  59. #[cfg(not(target_os = "android"))]
  60. static ALLOW_TRACE: &[&'static str] = &["ui", "app", "gfx", "plugin", "app", "main"];
  61. #[cfg(all(target_os = "android", feature = "enable-filelog"))]
  62. fn logfile_path() -> PathBuf {
  63. use crate::android::get_external_storage_path;
  64. get_external_storage_path().join("darkfi-app.log")
  65. }
  66. #[cfg(all(not(target_os = "android"), feature = "enable-filelog"))]
  67. fn logfile_path() -> PathBuf {
  68. dirs::cache_dir().unwrap().join("darkfi/darkfi-app.log")
  69. }
  70. // On Android, resolving the log path is a JNI call into the JVM, which can
  71. // deadlock if invoked from the panic hook. We therefore resolve it once at
  72. // startup (before the panic hook is installed) and cache it here, so the
  73. // hook only performs an atomic load plus a synchronous file write.
  74. #[cfg(feature = "enable-filelog")]
  75. static LOGFILE_PATH: OnceLock<PathBuf> = OnceLock::new();
  76. #[cfg(feature = "enable-filelog")]
  77. pub fn init_logfile_path() {
  78. let _ = LOGFILE_PATH.set(logfile_path());
  79. }
  80. #[cfg(feature = "enable-filelog")]
  81. pub fn cached_logfile_path() -> Option<&'static std::path::Path> {
  82. LOGFILE_PATH.get().map(|path| path.as_path())
  83. }
  84. #[cfg(not(feature = "enable-filelog"))]
  85. pub fn cached_logfile_path() -> Option<&'static std::path::Path> {
  86. None
  87. }
  88. pub fn setup_logging() -> Option<WorkerGuard> {
  89. let mut layers: Vec<(Box<dyn Layer<Registry> + Send + Sync>, Option<WorkerGuard>)> = vec![];
  90. #[cfg(feature = "enable-filelog")]
  91. {
  92. let (non_blocking_file_rotate, guard) = tracing_appender::non_blocking(FileRotate::new(
  93. LOGFILE_PATH.get_or_init(logfile_path).clone(),
  94. AppendCount::new(0),
  95. ContentLimit::BytesSurpassed(LOGFILE_MAXSIZE),
  96. Compression::None,
  97. #[cfg(unix)]
  98. None,
  99. ));
  100. let file_layer = tracing_subscriber::fmt::Layer::new()
  101. .event_format(EventFormatter::new(false, true))
  102. .fmt_fields(tracing_subscriber::fmt::format::debug_fn(
  103. darkfi::util::logger::file_field_formatter,
  104. ))
  105. .with_writer(non_blocking_file_rotate)
  106. .with_filter(
  107. TargetFilter::default()
  108. .ignore_targets([
  109. "sled",
  110. "rustls",
  111. "async_io",
  112. "polling",
  113. "turso_core",
  114. "turso_sqlite",
  115. "walletdb",
  116. "rpc::client",
  117. ])
  118. .targets_level(["log", "pulseaudio"], Level::Warn)
  119. .default_level(Level::Trace),
  120. );
  121. layers.push((file_layer.boxed(), Some(guard)));
  122. }
  123. #[cfg(target_os = "android")]
  124. {
  125. let logcat_layer =
  126. tracing_android::layer("darkfi").expect("tracing_android layer").with_filter(
  127. Targets::new()
  128. .with_targets(
  129. crate::logger::MUTED_TARGETS.iter().map(|&t| (t, LevelFilter::OFF)),
  130. )
  131. .with_default(LevelFilter::TRACE),
  132. );
  133. layers.push((logcat_layer.boxed(), None));
  134. }
  135. #[cfg(not(target_os = "android"))]
  136. {
  137. let terminal_layer = tracing_subscriber::fmt::Layer::new()
  138. //.with_span_events(FmtSpan::ENTER | FmtSpan::CLOSE)
  139. .event_format(EventFormatter::new(true, true))
  140. .fmt_fields(tracing_subscriber::fmt::format::debug_fn(
  141. darkfi::util::logger::terminal_field_formatter,
  142. ))
  143. .with_writer(std::io::stdout)
  144. .with_filter(
  145. TargetFilter::default()
  146. .targets_level(ALLOW_TRACE, Level::Trace)
  147. .targets_level(MUTED_TARGETS, Level::Info)
  148. .default_level(Level::Debug),
  149. );
  150. layers.push((terminal_layer.boxed(), None));
  151. }
  152. let file_logging_guard = layers.iter_mut().find_map(|l| l.1.take());
  153. Registry::default()
  154. .with(layers.into_iter().map(|l| l.0).collect::<Vec<_>>())
  155. .try_init()
  156. .expect("logger");
  157. file_logging_guard
  158. }