GithubHelp home page GithubHelp logo

Comments (1)

emabee avatar emabee commented on July 22, 2024

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

from flexi_logger.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.