anvil/
logging.rs

1//! User facing Logger
2
3use parking_lot::RwLock;
4use std::sync::Arc;
5use tracing::{subscriber::Interest, Metadata};
6use tracing_subscriber::{layer::Context, Layer};
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        if metadata.target() == NODE_USER_LOG_TARGET || metadata.target() == EVM_CONSOLE_LOG_TARGET
37        {
38            Interest::sometimes()
39        } else {
40            Interest::never()
41        }
42    }
43
44    fn enabled(&self, metadata: &Metadata<'_>, _ctx: Context<'_, S>) -> bool {
45        self.state.is_enabled() &&
46            (metadata.target() == NODE_USER_LOG_TARGET ||
47                metadata.target() == EVM_CONSOLE_LOG_TARGET)
48    }
49}
50
51/// Contains the configuration of the logger
52#[derive(Clone, Debug)]
53pub struct LoggingManager {
54    /// Whether the logger is currently enabled
55    pub enabled: Arc<RwLock<bool>>,
56}
57
58impl LoggingManager {
59    /// Returns true if logging is currently enabled
60    pub fn is_enabled(&self) -> bool {
61        *self.enabled.read()
62    }
63
64    /// Updates the `enabled` state
65    pub fn set_enabled(&self, enabled: bool) {
66        let mut current = self.enabled.write();
67        *current = enabled;
68    }
69}
70
71impl Default for LoggingManager {
72    fn default() -> Self {
73        Self { enabled: Arc::new(RwLock::new(true)) }
74    }
75}