Skip to main content

anvil_polkadot/
logging.rs

1//! User facing Logger
2
3use parking_lot::RwLock;
4use std::sync::Arc;
5use tracing::{Metadata, subscriber::Interest};
6use tracing_subscriber::{Layer, layer::Context};
7
8/// The target that identifies the events intended to be logged to stdout
9pub(crate) const NODE_USER_LOG_TARGET: &str = "node::user";
10
11/// The target that identifies the events coming from the `console.log` invocations.
12pub(crate) const EVM_CONSOLE_LOG_TARGET: &str = "node::console";
13
14/// A logger that listens for node related events and displays them.
15///
16/// This layer is intended to be used as filter for `NODE_USER_LOG_TARGET` events that will
17/// eventually be logged to stdout
18#[derive(Clone, Debug, Default)]
19pub struct NodeLogLayer {
20    state: LoggingManager,
21}
22
23impl NodeLogLayer {
24    /// Returns a new instance of this layer
25    pub fn new(state: LoggingManager) -> Self {
26        Self { state }
27    }
28}
29
30// use `Layer`'s filter function to globally enable/disable `NODE_USER_LOG_TARGET` events
31impl<S> Layer<S> for NodeLogLayer
32where
33    S: tracing::Subscriber,
34{
35    fn register_callsite(&self, metadata: &'static Metadata<'static>) -> Interest {
36        // Use Interest::sometimes() for node targets to enable dynamic filtering
37        match metadata.target() {
38            NODE_USER_LOG_TARGET | EVM_CONSOLE_LOG_TARGET => Interest::sometimes(),
39            _ => Interest::always(),
40        }
41    }
42
43    fn enabled(&self, metadata: &Metadata<'_>, _ctx: Context<'_, S>) -> bool {
44        // Only gate node targets, let everything else pass through
45        match metadata.target() {
46            NODE_USER_LOG_TARGET | EVM_CONSOLE_LOG_TARGET => self.state.is_enabled(),
47            _ => true,
48        }
49    }
50}
51
52/// Contains the configuration of the logger
53#[derive(Clone, Debug)]
54pub struct LoggingManager {
55    /// Whether the logger is currently enabled
56    pub enabled: Arc<RwLock<bool>>,
57}
58
59impl LoggingManager {
60    /// Returns true if logging is currently enabled
61    pub fn is_enabled(&self) -> bool {
62        *self.enabled.read()
63    }
64
65    /// Updates the `enabled` state
66    pub fn set_enabled(&self, enabled: bool) {
67        let mut current = self.enabled.write();
68        *current = enabled;
69    }
70}
71
72impl Default for LoggingManager {
73    fn default() -> Self {
74        Self { enabled: Arc::new(RwLock::new(true)) }
75    }
76}