Átila Gama Silva
Átila Gama Silva

Reputation: 33

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

Is it possible to do something like this in macros of the log crate?

enum ErrorKind {
    KindA,
    KindB,
    KindC,
}

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

In the log function of the custom logger:

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(),
       }
    }
}

Upvotes: 0

Views: 384

Answers (1)

Ibraheem Ahmed
Ibraheem Ahmed

Reputation: 13538

The log macros act very similar to println! in that you can overload them with arguments as long as they implement std::fmt::Display. You can implement fmt::Display for the ErrorKind enum manually in order to write custom responses based on the enum variant:

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"),
    }
  }
}

Now, you can use the log macros with 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

Upvotes: 1

Related Questions