3

If I uncomment create_log, both log and LOG are printed on the console. Without it, nothing is printed. What is going on?

#[macro_use]
extern crate slog;
extern crate slog_term;
extern crate slog_async;
#[macro_use]
extern crate lazy_static;

use slog::Drain;

lazy_static! {
    static ref LOG: slog::Logger = create_log();
}

fn create_log() -> slog::Logger {
    let decorator = slog_term::TermDecorator::new().force_plain().build();
    let drain = slog_term::CompactFormat::new(decorator).build().fuse();
    let drain = slog_async::Async::new(drain).build().fuse();
    slog::Logger::root(drain, o!())
}

fn main() {
    info!(LOG, "LOG");  // NOT printed unless next line is uncommented

    // let log = create_log();     // enables printing both log and LOG
    // info!(log, "log");
}
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
magesh
  • 101
  • 7

1 Answers1

7

By using slog-async, you have opted into:

slog-async allows building Drains that offload processing to another thread. Typically serialization and IO operations can be slow enough that they could make logging hinder performance of the main code. Sending logging records to another thread is much faster (ballpark of 100ns).

Your code registers a log event which will be sent to another thread and then immediately exits. There wasn't any time for the background thread to actually log.

However, by putting a sleep at the end of your program, it "works":

std::thread::sleep_ms(1000);

Why does the other case work? Again, we turn to the docs, emphasis mine:

When using std::process::exit to terminate a process with an exit code it is imporant to notice that destructors will not be called. This matters for slog_async as it will prevents flushing of the async drain and discarding messages that are not yet written.

Items in lazy-static do not have their destructors run (when would they, if the point of it is to live forever).

When you construct another logger from the main function, it is allocated on the stack and will be dropped. This causes the previous log message to also be flushed.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366