message: feat: Add metrics filter
  Filter metrics via `log_enabled!` inside `metric!`.
diff: @@ -13,7 +13,7 @@ use std::path::PathBuf;
  use std::{fs, panic, thread};
  pub use log::{self as internal, Level, SetLoggerError};
  -pub use serde_json::json;
  +pub use serde_json::{json, Map, Value};
  #[doc(hidden)]
  #[macro_export]
  @@ -58,29 +58,31 @@ macro_rules! error {
  }
  }
  -/// Enable metrics collection feature by setting `ckb-metrics=trace` in logger filter.
  +/// Enable metrics collection via configuring log filter. Here are some examples:
  +/// * `filter=info,ckb-metrics=trace`: enable all metrics collection
  +/// * `filter=info,ckb-metrics=trace,ckb-metrics-sync=off`: enable all metrics collection except
  +/// topic "sync"
  +/// * `filter=info,ckb-metrics-sync=trace`: only enable metrics collection of topic "sync"
  #[macro_export(local_inner_macros)]
  macro_rules! metric {
  - ($( $args:tt )*) => {
  - let mut obj = $crate::json!($( $args )*);
  - if obj.get("fields").is_none() {
  - obj.as_object_mut()
  - .map(|obj| obj.insert(String::from("fields"), $crate::json!({})));
  - }
  - if obj.get("tags").is_none() {
  - obj.as_object_mut()
  - .map(|obj| obj.insert(String::from("tags"), $crate::json!({})));
  - }
  - obj.get_mut("tags")
  - .and_then(|tags| {
  - tags.as_object_mut()
  - .map(|tags|
  - if !tags.contains_key("target") {
  - tags.insert(String::from("target"), $crate::env!("CARGO_PKG_NAME").into());
  + ( { $( $args:tt )* } ) => {
  + let topic = $crate::__metric_topic!( $($args)* );
  + let filter = ::std::format!("ckb-metrics-{}", topic);
  + if $crate::log_enabled_target!(&filter, $crate::Level::Trace) {
  + let mut metric = $crate::json!( { $( $args )* });
  + $crate::__log_metric(&mut metric, $crate::env!("CARGO_PKG_NAME"));
  }
  - )
  - });
  - $crate::internal::trace!(target: "ckb-metrics", "{}", obj);
  + }
  +}
  +
  +#[doc(hidden)]
  +#[macro_export(local_inner_macros)]
  +macro_rules! __metric_topic {
  + ("topic" : $topic:expr , $($_args:tt)*) => {
  + $topic
  + };
  + ($_key:literal : $_val:tt , $($args:tt)+) => {
  + $crate::__metric_topic!($($args)+)
  }
  }
  @@ -336,3 +338,25 @@ fn setup_panic_logger() {
  };
  panic::set_hook(Box::new(panic_logger));
  }
  +
  +// Used inside macro `metric!`
  +pub fn __log_metric(metric: &mut Value, default_target: &str) {
  + if metric.get("fields").is_none() {
  + metric
  + .as_object_mut()
  + .map(|obj| obj.insert("fields".to_string(), Map::new().into()));
  + }
  + if metric.get("tags").is_none() {
  + metric
  + .as_object_mut()
  + .map(|obj| obj.insert("tags".to_string(), Map::new().into()));
  + }
  + metric.get_mut("tags").and_then(|tags| {
  + tags.as_object_mut().map(|tags| {
  + if !tags.contains_key("target") {
  + tags.insert("target".to_string(), default_target.into());
  + }
  + })
  + });
  + trace_target!("ckb-metrics", "{}", metric);
  +}
  