emabee / flexi_logger

A flexible logger for rust programs that can write to stderr, stdout, and/or to log files
Apache License 2.0
307 stars 50 forks source link

How to reopen the output file of a FileLogWriter after Logger::add_writer took it over? #143

Closed brainpower closed 1 year ago

brainpower commented 1 year ago
let filespec = FileSpec::try_from("access.log")?.suppress_timestamp();
let awriter = FileLogWriter::builder(filespec).append().try_build()?;
let logger_handle = Logger::try_with_env_or_str("info")?
      .add_writer("AccessLog", awriter)
      .start()?; 

In this code which was derived from the example here, awriter gets moved into the Logger by add_writer. Later I want to tell the awriter to reopen its output files, when SIGHUP is received but I could not find a way to do this.

Things I've tried:

So: How can I get the awriter to reopen its log file in a sighup handler?

fn handle_sighup(lh: LoggerHandle) -> Result<(), Box<dyn std::error::Error>> {
  // somehow tell the logger to reopen the logfile of awriter here...

  // this does not print any logfiles, even though logging to the file works fine:
  eprintln!("logfiles: {:?}", lh.existing_log_files());

  // this does not work, it returns NoFileLogger error:
  lh.reopen_outputfile()
}

(Sorry, if I'm missing some obvious core rust thing that could be used here to keep a reference to awriter, I'm fairly new to rust.)

emabee commented 1 year ago

The method LoggerHandle::reopen_output() (name has slightly changed) now cares for all configured writers.

brainpower commented 1 year ago

Just tried this new method in my project and it worked nicely! Thanks!