Created
February 18, 2023 19:20
-
-
Save eirenik0/a6c7c5be32d5e55a0e73b2e26762bb54 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// Allow to redirect logs from process stdout, stderr to tracing log. | |
/// | |
/// # Examples | |
/// | |
/// ```ignore | |
/// use std::process::Stdio; | |
/// use tokio::process::Command; | |
/// use ephyr_log::{log, init, Level, run_log_redirect}; | |
/// | |
/// init(Some(Level::INFO)); | |
/// let mut process = Command::new("/bin/ls") | |
/// .stdin(Stdio::null()) | |
/// .stdout(Stdio::piped()) | |
/// .stderr(Stdio::piped()) | |
/// .spawn().map_err(|e| { | |
/// log::error!("Failed run: {e}"); | |
/// })?; | |
/// run_log_redirect(process.stdout.take(), |line| { | |
/// log::debug!("{}", &line); | |
/// })?; | |
/// ``` | |
pub fn run_log_redirect<R, F>(src: Option<R>, to: F) | |
where | |
R: AsyncRead + Unpin + Send + 'static, | |
F: Fn(String) + Send + 'static, | |
{ | |
if let Some(src) = src { | |
let buff = BufReader::new(src); | |
drop(tokio::spawn(async move { | |
let mut lines = buff.lines(); | |
while let Some(line) = | |
lines.next_line().await.unwrap_or_else(|_| { | |
Some("Failed to fetch log line".to_string()) | |
}) | |
{ | |
to(line); | |
} | |
})); | |
} else { | |
tracing::event!(Level::ERROR, "Failed to fetch log line"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment