emabee / flexi_logger

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

Dynamic logging for parent/daemon #144

Closed AustinScola closed 9 months ago

AustinScola commented 1 year ago

I have a program that starts a daemon and I want to have two different logging configurations:

flexi_logger doesn't seem to quite have this ability yet? The best I would be able to do is also have the parent write to the log file, duplicate to stdout, and then when the daemon is created turn off duplication. The problem with this is that I don't want the parent's output in the log file.

emabee commented 9 months ago

The crucial point is not to start the logger before spawning (or forking).

This example does what you want:

use flexi_logger::{DeferredNow, FileSpec, LogSpecification, Logger};
use log::{error, info, trace, Record};
use std::process::Command;

fn main() -> Result<(), anyhow::Error> {
    // don't set up logger here, it prevents any logger set up later here or in the child
    let mut args = std::env::args();
    let progname = args.next().unwrap();
    if args.next().is_none() {
        run_as_parent(&progname);
    } else {
        run_as_child();
    }
    Ok(())
}

fn run_as_parent(progname: &str) {
    // spawn the child, then set up the parent's logger
    let mut child = Command::new(progname)
        .arg("child")
        .spawn()
        .expect("Failed to start child process");

    let _logger = Logger::with(LogSpecification::info())
        .log_to_stdout()
        .format(parent_format)
        .start()
        .expect("Failed to start logger in the parent");

    info!("Do parent work");
    info!("Waiting for the child");
    error!("Child is late for coming home!");
    let child_exit_status = child.wait().expect("failed to wait on child");
    info!("Child returned with {child_exit_status}");
}

fn run_as_child() {
    let _logger = Logger::with(LogSpecification::trace())
        .format(child_format)
        .log_to_file(FileSpec::default())
        .duplicate_to_stdout(flexi_logger::Duplicate::Info)
        .start()
        .expect("Failed to start logger in the child");

    info!("Going to the playground");
    trace!("Playing");
}

pub fn parent_format(
    w: &mut dyn std::io::Write,
    _now: &mut DeferredNow,
    record: &Record,
) -> Result<(), std::io::Error> {
    write!(
        w,
        "[Parent] {} [{}] {}",
        record.level(),
        record.module_path().unwrap_or("<unnamed>"),
        record.args()
    )
}

pub fn child_format(
    w: &mut dyn std::io::Write,
    _now: &mut DeferredNow,
    record: &Record,
) -> Result<(), std::io::Error> {
    write!(
        w,
        "[Child] {} [{}] {}",
        record.level(),
        record.module_path().unwrap_or("<unnamed>"),
        record.args()
    )
}

When running the program, you get the output of parent and child intermixed in stdout. The log file only contains entries from the child.

>> dummy
[Parent] INFO [dummy] Do parent work
[Parent] INFO [dummy] Waiting for the child
[Parent] ERROR [dummy] Child is late for coming home!
[Child] INFO [dummy] Going to the playground
[Parent] INFO [dummy] Child returned with exit status: 0
>> cat dummy_2024-01-22_19-56-34.log
[Child] INFO [dummy] Going to the playground
[Child] TRACE [dummy] Playing