rustchild-processrust-tracing

How to redirect logs from Command output to tracing?


I'm adopting tracing as logging tool for my Rust app. I want to have all logs go through tracing. In the future, it will handle send logs to monitoring tool.

The app works by invoking multiple processes. Previously they were printing to stdin and all logs were visible. Those processes ran with Command and tokio::spawn.

I would like to redirect the output from the Command to tracing, but not sure how to do that.


Solution

  • The result of calling std::Command::output is a Result<Output> and the Output struct has public stdout and stderr Vec<u8> fields.

    So like Nikolay wrote, you can can tracing::info! to output each of the field values.

    But if the existing code was writing to the stdout and stderr of the app itself, maybe std::Command::spawn was being used? You may want to continue using this spawn method and taking the stdout and stderr from the child as shown in std::process::Child and then actually spawning new threads to read from the stdout and stderr to pass the data to tracing macros like info!.

    I doubt the tracing library would have a canned way of doing this because subprocess stdout and stderr could be formatted in so many ways.

    But if you expect the output to be short and no parsing is necessary, then passing the stdout and stderr vecs to info! should do the trick as mentioned above.