gpt4 book ai didi

logging - 如何在Rust中将自定义数据传递到日志箱的宏?

转载 作者:行者123 更新时间:2023-12-03 11:44:34 26 4
gpt4 key购买 nike

是否可以在log条板箱的宏中执行类似的操作?

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,就可以用参数重载它们。您可以手动为fmt::Display枚举实现ErrorKind,以便基于enum变体编写自定义响应:

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

关于logging - 如何在Rust中将自定义数据传递到日志箱的宏?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64599228/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com