How to disable the logging outputs of specific instances?

Hello, rustaceans.
I am working on a tiny lab and I have a problem about how to disable the logging outputs of specific instances.
Below is the codes.

struct Instace {
impl Instance {
    fn new() -> Instance {
        // spawn some threads to work.
        // these threads will produce some logging output.
    fn kill(&self) {
        // disable the logging output of the threads and return immediately.
fn main() {
    let ins1 = Instance::new();
    // do some work
    let ins2 = Instance::new();
    // do some work

The main function will create many instances and do some work to check if these instances work properly.
After the checking finished, the main function will call kill() to disable the logging output of the created instance to avoid the logging outputs of difference instances produced together.
Do you have any ideas about how to implement kill() ?
Any help will be appreciated!

Use an AtomicBool to store whether or not to log and check it every time you call log.

You will probably need an Arc to share the boolean between the threads.

1 Like

But is there any convenient way to implement it, such as use

my_info!("val1:{}, val2: {}", val1, val2);

to replace

if should_log {
    info!("val1:{}, val2: {}", val1, val2);

so that should_log doesn't appear everywhere.

Sure you can! You have to pass self to the macro to allow it to access the local variable, but here you go: playground.

Note that the example here uses println, but it can just be replaced with info.

1 Like

Thank you! It helps me a lot.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.