Comments (1)
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)
- Get all log files include rolling
- There is no line number in the log? HOT 2
- Option to disable stderr/stdout output? HOT 4
- How to reopen the output file of a FileLogWriter after Logger::add_writer took it over? HOT 2
- bufsize in std_writer::AsyncHandle HOT 2
- Missing `regex` and `log` dependencies - fail to compile HOT 1
- Method on LoggerHandle for manually forcing rotation?
- Remove remnants of the external_rotation feature
- Rotation may overwrite existing log file HOT 9
- Different logger instances per thread? HOT 1
- GlobError unwrap happens HOT 3
- [trc] Improve usability by getting values from `Logger` or integrating with it HOT 1
- `kv` support from log crate. Json formatter. HOT 2
- Does this library support multiple log files and/or multiple named/filtered outputs? HOT 1
- Add new file logged on the fly HOT 8
- creating vs modification time HOT 1
- TimestampsCustomFormat with empty current_infix HOT 1
- FileLogWriter does not follow its max_level HOT 1
- Custom logging level HOT 1
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
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.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from flexi_logger.