jl0x61
jl0x61

Reputation: 447

How to add specific prefix to the logging output in Rust?

I have an object and want every logging output to be prefixed with some states of the object. But adding prefix for every logging statement is very inconvenient. Is there any simple way to implement it?

Below is the sample code.

use log::info;

struct Obj {
    id: i32,
    name: String,
}

impl Obj {
    // can I use `info!("receive {} from {}", item, from);` for simplicity?
    fn call_me(&self, item: i32, from: String) {
        info!("[id: {}][name: {}] receive {} from {}", self.id, self.name, item, from);
    }
    // ...many methods
}

Any help will be appreciated!

Upvotes: 6

Views: 1443

Answers (1)

Denys Séguret
Denys Séguret

Reputation: 382194

You could write a macro for this:

#[macro_export]
macro_rules! log {
    ($sel:ident, $s:literal, $($arg:tt)*)
    =>
    (info!(concat!("[id: {}] [name: {}] ", $s), $sel.id, $sel.name, $($arg)*));
}

struct Obj {
    id: i32,
    name: String,
}

impl Obj {
    fn call_me(&self, item: i32, from: String) {
        log!(self, "receive {} from {}", item, from);
    }
}

It's not perfect, as you still need to pass self, but I'm not sure you can do better.

playground

Upvotes: 8

Related Questions