如何将自定义数据传递给 Rust 中 log crate 的宏?

How to pass custom data to macros of log crate in Rust?

是否可以在 log crate 的宏中做这样的事情?

enum ErrorKind {
    KindA,
    KindB,
    KindC,
}

error!(ErrorKind::KindA, "Unable to do A.");

在自定义记录器的日志函数中:

fn log(&self, record: &Record) {
    if self.enabled(record.metadata()) {
       match record.custom_args.kind {
           KindA => handle_kind_a(),
           KindB => handle_kind_b(),
           KindC => handle_kind_c(),
       }
    }
}

日志宏的行为与 println! 非常相似,只要它们实现 std::fmt::Display,您就可以用参数重载它们。您可以手动为 ErrorKind 枚举实现 fmt::Display,以便根据枚举变体编写自定义响应:

impl std::fmt::Display for ErrorKind {
  fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
    match *self {
      ErrorKind::KindA => write!(f, "ErrorKind is of type KindA"),
      ErrorKind::KindB => write!(f, "ErrorKind is of type KindB"),
      ErrorKind::KindC => write!(f, "ErrorKind is of type KindC"),
    }
  }
}

现在,您可以将日志宏与 ErrorKind 一起使用:

error!("Unable to do A: {}", ErrorKind::KindA);
// => Unable to do A: ErrorKind is of type KindA

error!("Unable to do A: {}", ErrorKind::KindB);
// => Unable to do A: ErrorKind is of type KindB

error!("Unable to do A: {}", ErrorKind::KindC);
// => Unable to do A: ErrorKind is of type KindC