-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Extract logging.rs. - Fix edge case: when remote `log_dir` becomes `None`, the logs will be printed to stdout if the stdout is not set for logging.
- Loading branch information
Showing
2 changed files
with
123 additions
and
133 deletions.
There are no files selected for viewing
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,111 @@ | ||
use std::fs::{create_dir_all, OpenOptions}; | ||
use std::path::Path; | ||
|
||
use anyhow::{anyhow, bail, Result}; | ||
use tracing::info; | ||
use tracing::metadata::LevelFilter; | ||
use tracing_appender::non_blocking::WorkerGuard; | ||
use tracing_subscriber::reload; | ||
use tracing_subscriber::{ | ||
fmt, prelude::__tracing_subscriber_SubscriberExt, util::SubscriberInitExt, EnvFilter, Layer, | ||
}; | ||
|
||
type ChangeLogDir = Box<dyn Fn(Option<&Path>, Option<&Path>) -> Result<Option<WorkerGuard>>>; | ||
|
||
/// Manages the log file and guards. | ||
/// | ||
/// `guards` will flush the logs when it's dropped. | ||
/// | ||
/// `change_log_dir` wraps the log file to allow changing its path dynamically. | ||
/// If the log file is not provided, logs will be ignored by using `std::io::sink()`. | ||
pub struct LogManager { | ||
pub guard: WorkerGuard, | ||
pub change_log_dir: ChangeLogDir, | ||
} | ||
|
||
/// Creates a writer for the `default_layer`. | ||
/// | ||
/// If runtime is in debug mode, `debug_layer` will be used to print logs to stdout. So this function | ||
/// return `std::io::sink()` to avoid duplicated logs in stdout. | ||
fn create_writer(dir_path: Option<&Path>) -> Result<Box<dyn std::io::Write + Send>> { | ||
if dir_path.is_none() { | ||
if cfg!(debug_assertions) { | ||
return Ok(Box::new(std::io::sink())); | ||
} | ||
return Ok(Box::new(std::io::stdout())); | ||
} | ||
|
||
let dir_path = dir_path.expect("Verified by is_none"); | ||
|
||
if let Err(e) = create_dir_all(dir_path) { | ||
bail!("Cannot create the directory recursively for {dir_path:?}: {e}"); | ||
} | ||
|
||
let file_name = format!("{}.log", env!("CARGO_PKG_NAME")); | ||
|
||
let file = OpenOptions::new() | ||
.create(true) | ||
.append(true) | ||
.open(dir_path.join(file_name)) | ||
.map_err(|e| anyhow!("Cannot create the log file: {e}")); | ||
|
||
file.map(|f| Box::new(f) as Box<dyn std::io::Write + Send>) | ||
} | ||
|
||
/// Initializes the tracing subscriber. | ||
/// | ||
/// If `log_dir` is `None` or the runtime is in debug mode, logs will be printed to stdout. | ||
pub fn init_tracing(log_dir: Option<&Path>) -> Result<LogManager> { | ||
let debug_layer = if cfg!(debug_assertions) { | ||
Some( | ||
fmt::Layer::default() | ||
.with_ansi(true) | ||
.with_filter(EnvFilter::from_default_env()), | ||
) | ||
} else { | ||
None | ||
}; | ||
|
||
let writer = create_writer(log_dir)?; | ||
let (non_blocking_writer, guard) = tracing_appender::non_blocking(writer); | ||
let (default_layer, reload_handle) = reload::Layer::new( | ||
fmt::Layer::default() | ||
.with_ansi(false) | ||
.with_target(false) | ||
.with_writer(non_blocking_writer) | ||
.with_filter( | ||
EnvFilter::builder() | ||
.with_default_directive(LevelFilter::INFO.into()) | ||
.from_env_lossy(), | ||
), | ||
); | ||
|
||
let change_log_dir: ChangeLogDir = | ||
Box::new(move |old_dir: Option<&Path>, new_dir: Option<&Path>| { | ||
if old_dir.eq(&new_dir) { | ||
info!("New log directory is the same as the old directory"); | ||
return Ok(None); | ||
} | ||
let writer = create_writer(new_dir)?; | ||
if let Some(dir) = new_dir { | ||
info!("Log directory will change to {}", dir.display()); | ||
} | ||
let (writer, guard) = tracing_appender::non_blocking(writer); | ||
reload_handle.modify(|layer| { | ||
*layer.inner_mut().writer_mut() = writer; | ||
})?; | ||
if let Some(dir) = old_dir { | ||
info!("Previous logs are in {}", dir.display()); | ||
} | ||
Ok(Some(guard)) | ||
}); | ||
|
||
tracing_subscriber::Registry::default() | ||
.with(debug_layer) | ||
.with(default_layer) | ||
.init(); | ||
Ok(LogManager { | ||
guard, | ||
change_log_dir, | ||
}) | ||
} |
This file contains 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