LCOV - code coverage report
Current view: top level - libs/utils/src - logging.rs (source / functions) Coverage Total Hit
Test: 09e7485004805bd42b53a0c369170b3228136512.info Lines: 59.9 % 167 100
Test Date: 2024-11-21 18:36:18 Functions: 51.7 % 29 15

            Line data    Source code
       1              : use std::str::FromStr;
       2              : 
       3              : use anyhow::Context;
       4              : use metrics::{IntCounter, IntCounterVec};
       5              : use once_cell::sync::Lazy;
       6              : use strum_macros::{EnumString, VariantNames};
       7              : 
       8          210 : #[derive(EnumString, strum_macros::Display, VariantNames, Eq, PartialEq, Debug, Clone, Copy)]
       9              : #[strum(serialize_all = "snake_case")]
      10              : pub enum LogFormat {
      11              :     Plain,
      12              :     Json,
      13              :     Test,
      14              : }
      15              : 
      16              : impl LogFormat {
      17            0 :     pub fn from_config(s: &str) -> anyhow::Result<LogFormat> {
      18              :         use strum::VariantNames;
      19            0 :         LogFormat::from_str(s).with_context(|| {
      20            0 :             format!(
      21            0 :                 "Unrecognized log format. Please specify one of: {:?}",
      22            0 :                 LogFormat::VARIANTS
      23            0 :             )
      24            0 :         })
      25            0 :     }
      26              : }
      27              : 
      28              : struct TracingEventCountMetric {
      29              :     error: IntCounter,
      30              :     warn: IntCounter,
      31              :     info: IntCounter,
      32              :     debug: IntCounter,
      33              :     trace: IntCounter,
      34              : }
      35              : 
      36          268 : static TRACING_EVENT_COUNT_METRIC: Lazy<TracingEventCountMetric> = Lazy::new(|| {
      37          268 :     let vec = metrics::register_int_counter_vec!(
      38          268 :         "libmetrics_tracing_event_count",
      39          268 :         "Number of tracing events, by level",
      40          268 :         &["level"]
      41          268 :     )
      42          268 :     .expect("failed to define metric");
      43          268 :     TracingEventCountMetric::new(vec)
      44          268 : });
      45              : 
      46              : impl TracingEventCountMetric {
      47          269 :     fn new(vec: IntCounterVec) -> Self {
      48          269 :         Self {
      49          269 :             error: vec.with_label_values(&["error"]),
      50          269 :             warn: vec.with_label_values(&["warn"]),
      51          269 :             info: vec.with_label_values(&["info"]),
      52          269 :             debug: vec.with_label_values(&["debug"]),
      53          269 :             trace: vec.with_label_values(&["trace"]),
      54          269 :         }
      55          269 :     }
      56              : 
      57        25400 :     fn inc_for_level(&self, level: tracing::Level) {
      58        25400 :         let counter = match level {
      59           69 :             tracing::Level::ERROR => &self.error,
      60          221 :             tracing::Level::WARN => &self.warn,
      61        25108 :             tracing::Level::INFO => &self.info,
      62            1 :             tracing::Level::DEBUG => &self.debug,
      63            1 :             tracing::Level::TRACE => &self.trace,
      64              :         };
      65        25400 :         counter.inc();
      66        25400 :     }
      67              : }
      68              : 
      69              : struct TracingEventCountLayer(&'static TracingEventCountMetric);
      70              : 
      71              : impl<S> tracing_subscriber::layer::Layer<S> for TracingEventCountLayer
      72              : where
      73              :     S: tracing::Subscriber,
      74              : {
      75        25400 :     fn on_event(
      76        25400 :         &self,
      77        25400 :         event: &tracing::Event<'_>,
      78        25400 :         _ctx: tracing_subscriber::layer::Context<'_, S>,
      79        25400 :     ) {
      80        25400 :         self.0.inc_for_level(*event.metadata().level());
      81        25400 :     }
      82              : }
      83              : 
      84              : /// Whether to add the `tracing_error` crate's `ErrorLayer`
      85              : /// to the global tracing subscriber.
      86              : ///
      87              : pub enum TracingErrorLayerEnablement {
      88              :     /// Do not add the `ErrorLayer`.
      89              :     Disabled,
      90              :     /// Add the `ErrorLayer` with the filter specified by RUST_LOG, defaulting to `info` if `RUST_LOG` is unset.
      91              :     EnableWithRustLogFilter,
      92              : }
      93              : 
      94              : /// Where the logging should output to.
      95              : #[derive(Clone, Copy)]
      96              : pub enum Output {
      97              :     Stdout,
      98              :     Stderr,
      99              : }
     100              : 
     101          268 : pub fn init(
     102          268 :     log_format: LogFormat,
     103          268 :     tracing_error_layer_enablement: TracingErrorLayerEnablement,
     104          268 :     output: Output,
     105          268 : ) -> anyhow::Result<()> {
     106          268 :     // We fall back to printing all spans at info-level or above if
     107          268 :     // the RUST_LOG environment variable is not set.
     108          734 :     let rust_log_env_filter = || {
     109          734 :         tracing_subscriber::EnvFilter::try_from_default_env()
     110          734 :             .unwrap_or_else(|_| tracing_subscriber::EnvFilter::new("info"))
     111          734 :     };
     112              : 
     113              :     // NB: the order of the with() calls does not matter.
     114              :     // See https://docs.rs/tracing-subscriber/0.3.16/tracing_subscriber/layer/index.html#per-layer-filtering
     115              :     use tracing_subscriber::prelude::*;
     116          268 :     let r = tracing_subscriber::registry();
     117          268 :     let r = r.with({
     118          268 :         let log_layer = tracing_subscriber::fmt::layer()
     119          268 :             .with_target(false)
     120          268 :             .with_ansi(false)
     121          268 :             .with_writer(move || -> Box<dyn std::io::Write> {
     122            0 :                 match output {
     123            0 :                     Output::Stdout => Box::new(std::io::stdout()),
     124            0 :                     Output::Stderr => Box::new(std::io::stderr()),
     125              :                 }
     126          268 :             });
     127          268 :         let log_layer = match log_format {
     128            0 :             LogFormat::Json => log_layer.json().boxed(),
     129            0 :             LogFormat::Plain => log_layer.boxed(),
     130          268 :             LogFormat::Test => log_layer.with_test_writer().boxed(),
     131              :         };
     132          268 :         log_layer.with_filter(rust_log_env_filter())
     133          268 :     });
     134          268 :     let r = r.with(
     135          268 :         TracingEventCountLayer(&TRACING_EVENT_COUNT_METRIC).with_filter(rust_log_env_filter()),
     136          268 :     );
     137          268 :     match tracing_error_layer_enablement {
     138          198 :         TracingErrorLayerEnablement::EnableWithRustLogFilter => r
     139          198 :             .with(tracing_error::ErrorLayer::default().with_filter(rust_log_env_filter()))
     140          198 :             .init(),
     141           70 :         TracingErrorLayerEnablement::Disabled => r.init(),
     142              :     }
     143              : 
     144          268 :     Ok(())
     145          268 : }
     146              : 
     147              : /// Disable the default rust panic hook by using `set_hook`.
     148              : ///
     149              : /// For neon binaries, the assumption is that tracing is configured before with [`init`], after
     150              : /// that sentry is configured (if needed). sentry will install it's own on top of this, always
     151              : /// processing the panic before we log it.
     152              : ///
     153              : /// When the return value is dropped, the hook is reverted to std default hook (prints to stderr).
     154              : /// If the assumptions about the initialization order are not held, use
     155              : /// [`TracingPanicHookGuard::forget`] but keep in mind, if tracing is stopped, then panics will be
     156              : /// lost.
     157              : #[must_use]
     158            4 : pub fn replace_panic_hook_with_tracing_panic_hook() -> TracingPanicHookGuard {
     159            4 :     std::panic::set_hook(Box::new(tracing_panic_hook));
     160            4 :     TracingPanicHookGuard::new()
     161            4 : }
     162              : 
     163              : /// Drop guard which restores the std panic hook on drop.
     164              : ///
     165              : /// Tracing should not be used when it's not configured, but we cannot really latch on to any
     166              : /// imaginary lifetime of tracing.
     167              : pub struct TracingPanicHookGuard {
     168              :     act: bool,
     169              : }
     170              : 
     171              : impl TracingPanicHookGuard {
     172            4 :     fn new() -> Self {
     173            4 :         TracingPanicHookGuard { act: true }
     174            4 :     }
     175              : 
     176              :     /// Make this hook guard not do anything when dropped.
     177            4 :     pub fn forget(&mut self) {
     178            4 :         self.act = false;
     179            4 :     }
     180              : }
     181              : 
     182              : impl Drop for TracingPanicHookGuard {
     183            4 :     fn drop(&mut self) {
     184            4 :         if self.act {
     185            0 :             let _ = std::panic::take_hook();
     186            4 :         }
     187            4 :     }
     188              : }
     189              : 
     190              : /// Named symbol for our panic hook, which logs the panic.
     191            0 : fn tracing_panic_hook(info: &std::panic::PanicHookInfo) {
     192            0 :     // following rust 1.66.1 std implementation:
     193            0 :     // https://github.com/rust-lang/rust/blob/90743e7298aca107ddaa0c202a4d3604e29bfeb6/library/std/src/panicking.rs#L235-L288
     194            0 :     let location = info.location();
     195              : 
     196            0 :     let msg = match info.payload().downcast_ref::<&'static str>() {
     197            0 :         Some(s) => *s,
     198            0 :         None => match info.payload().downcast_ref::<String>() {
     199            0 :             Some(s) => &s[..],
     200            0 :             None => "Box<dyn Any>",
     201              :         },
     202              :     };
     203              : 
     204            0 :     let thread = std::thread::current();
     205            0 :     let thread = thread.name().unwrap_or("<unnamed>");
     206            0 :     let backtrace = std::backtrace::Backtrace::capture();
     207              : 
     208            0 :     let _entered = if let Some(location) = location {
     209            0 :         tracing::error_span!("panic", %thread, location = %PrettyLocation(location))
     210              :     } else {
     211              :         // very unlikely to hit here, but the guarantees of std could change
     212            0 :         tracing::error_span!("panic", %thread)
     213              :     }
     214            0 :     .entered();
     215            0 : 
     216            0 :     if backtrace.status() == std::backtrace::BacktraceStatus::Captured {
     217              :         // this has an annoying extra '\n' in the end which anyhow doesn't do, but we cannot really
     218              :         // get rid of it as we cannot get in between of std::fmt::Formatter<'_>; we could format to
     219              :         // string, maybe even to a TLS one but tracing already does that.
     220            0 :         tracing::error!("{msg}\n\nStack backtrace:\n{backtrace}");
     221              :     } else {
     222            0 :         tracing::error!("{msg}");
     223              :     }
     224              : 
     225              :     // ensure that we log something on the panic if this hook is left after tracing has been
     226              :     // unconfigured. worst case when teardown is racing the panic is to log the panic twice.
     227            0 :     tracing::dispatcher::get_default(|d| {
     228            0 :         if let Some(_none) = d.downcast_ref::<tracing::subscriber::NoSubscriber>() {
     229            0 :             let location = location.map(PrettyLocation);
     230            0 :             log_panic_to_stderr(thread, msg, location, &backtrace);
     231            0 :         }
     232            0 :     });
     233            0 : }
     234              : 
     235              : #[cold]
     236            0 : fn log_panic_to_stderr(
     237            0 :     thread: &str,
     238            0 :     msg: &str,
     239            0 :     location: Option<PrettyLocation<'_, '_>>,
     240            0 :     backtrace: &std::backtrace::Backtrace,
     241            0 : ) {
     242            0 :     eprintln!("panic while tracing is unconfigured: thread '{thread}' panicked at '{msg}', {location:?}\nStack backtrace:\n{backtrace}");
     243            0 : }
     244              : 
     245              : struct PrettyLocation<'a, 'b>(&'a std::panic::Location<'b>);
     246              : 
     247              : impl std::fmt::Display for PrettyLocation<'_, '_> {
     248            0 :     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
     249            0 :         write!(f, "{}:{}:{}", self.0.file(), self.0.line(), self.0.column())
     250            0 :     }
     251              : }
     252              : 
     253              : impl std::fmt::Debug for PrettyLocation<'_, '_> {
     254            0 :     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
     255            0 :         <Self as std::fmt::Display>::fmt(self, f)
     256            0 :     }
     257              : }
     258              : 
     259              : /// When you will store a secret but want to make sure it won't
     260              : /// be accidentally logged, wrap it in a SecretString, whose Debug
     261              : /// implementation does not expose the contents.
     262              : #[derive(Clone, Eq, PartialEq)]
     263              : pub struct SecretString(String);
     264              : 
     265              : impl SecretString {
     266            0 :     pub fn get_contents(&self) -> &str {
     267            0 :         self.0.as_str()
     268            0 :     }
     269              : }
     270              : 
     271              : impl From<String> for SecretString {
     272            0 :     fn from(s: String) -> Self {
     273            0 :         Self(s)
     274            0 :     }
     275              : }
     276              : 
     277              : impl FromStr for SecretString {
     278              :     type Err = std::convert::Infallible;
     279              : 
     280            0 :     fn from_str(s: &str) -> Result<Self, Self::Err> {
     281            0 :         Ok(Self(s.to_string()))
     282            0 :     }
     283              : }
     284              : 
     285              : impl std::fmt::Debug for SecretString {
     286            0 :     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
     287            0 :         write!(f, "[SECRET]")
     288            0 :     }
     289              : }
     290              : 
     291              : #[cfg(test)]
     292              : mod tests {
     293              :     use metrics::{core::Opts, IntCounterVec};
     294              : 
     295              :     use crate::logging::{TracingEventCountLayer, TracingEventCountMetric};
     296              : 
     297              :     #[test]
     298            1 :     fn tracing_event_count_metric() {
     299            1 :         let counter_vec =
     300            1 :             IntCounterVec::new(Opts::new("testmetric", "testhelp"), &["level"]).unwrap();
     301            1 :         let metric = Box::leak(Box::new(TracingEventCountMetric::new(counter_vec.clone())));
     302            1 :         let layer = TracingEventCountLayer(metric);
     303              :         use tracing_subscriber::prelude::*;
     304              : 
     305            1 :         tracing::subscriber::with_default(tracing_subscriber::registry().with(layer), || {
     306            1 :             tracing::trace!("foo");
     307            1 :             tracing::debug!("foo");
     308            1 :             tracing::info!("foo");
     309            1 :             tracing::warn!("foo");
     310            1 :             tracing::error!("foo");
     311            1 :         });
     312            1 : 
     313            1 :         assert_eq!(counter_vec.with_label_values(&["trace"]).get(), 1);
     314            1 :         assert_eq!(counter_vec.with_label_values(&["debug"]).get(), 1);
     315            1 :         assert_eq!(counter_vec.with_label_values(&["info"]).get(), 1);
     316            1 :         assert_eq!(counter_vec.with_label_values(&["warn"]).get(), 1);
     317            1 :         assert_eq!(counter_vec.with_label_values(&["error"]).get(), 1);
     318            1 :     }
     319              : }
        

Generated by: LCOV version 2.1-beta