use parking_lot::RwLock;
use std::sync::Arc;
use tracing::{subscriber::Interest, Metadata};
use tracing_subscriber::{layer::Context, Layer};
pub(crate) const NODE_USER_LOG_TARGET: &str = "node::user";
pub(crate) const EVM_CONSOLE_LOG_TARGET: &str = "node::console";
#[derive(Clone, Debug, Default)]
pub struct NodeLogLayer {
state: LoggingManager,
}
impl NodeLogLayer {
pub fn new(state: LoggingManager) -> Self {
Self { state }
}
}
impl<S> Layer<S> for NodeLogLayer
where
S: tracing::Subscriber,
{
fn register_callsite(&self, metadata: &'static Metadata<'static>) -> Interest {
if metadata.target() == NODE_USER_LOG_TARGET || metadata.target() == EVM_CONSOLE_LOG_TARGET
{
Interest::sometimes()
} else {
Interest::never()
}
}
fn enabled(&self, metadata: &Metadata<'_>, _ctx: Context<'_, S>) -> bool {
self.state.is_enabled() &&
(metadata.target() == NODE_USER_LOG_TARGET ||
metadata.target() == EVM_CONSOLE_LOG_TARGET)
}
}
#[derive(Clone, Debug)]
pub struct LoggingManager {
pub enabled: Arc<RwLock<bool>>,
}
impl LoggingManager {
pub fn is_enabled(&self) -> bool {
*self.enabled.read()
}
pub fn set_enabled(&self, enabled: bool) {
let mut current = self.enabled.write();
*current = enabled;
}
}
impl Default for LoggingManager {
fn default() -> Self {
Self { enabled: Arc::new(RwLock::new(true)) }
}
}