Add --no-buffering flag for the file logging.

This commit is contained in:
vsrs 2021-01-24 17:06:55 +03:00
parent 2c735ed734
commit 43fabfbe36
3 changed files with 21 additions and 15 deletions

View File

@ -14,6 +14,7 @@ use vfs::AbsPathBuf;
pub(crate) struct Args { pub(crate) struct Args {
pub(crate) verbosity: Verbosity, pub(crate) verbosity: Verbosity,
pub(crate) log_file: Option<PathBuf>, pub(crate) log_file: Option<PathBuf>,
pub(crate) no_buffering: bool,
pub(crate) command: Command, pub(crate) command: Command,
} }
@ -47,7 +48,8 @@ FLAGS:
-vv, --spammy -vv, --spammy
-q, --quiet Set verbosity -q, --quiet Set verbosity
--log-file <PATH> Log to the specified filed instead of stderr --log-file <PATH> Log to the specified file instead of stderr
--no-buffering Flush log records to the file immediatly
ENVIRONMENTAL VARIABLES: ENVIRONMENTAL VARIABLES:
RA_LOG Set log filter in env_logger format RA_LOG Set log filter in env_logger format
@ -114,6 +116,7 @@ impl Args {
verbosity: Verbosity::Normal, verbosity: Verbosity::Normal,
log_file: None, log_file: None,
command: Command::Version, command: Command::Version,
no_buffering: false,
}); });
} }
@ -130,21 +133,22 @@ impl Args {
(false, true, true) => bail!("Invalid flags: -q conflicts with -v"), (false, true, true) => bail!("Invalid flags: -q conflicts with -v"),
}; };
let log_file = matches.opt_value_from_str("--log-file")?; let log_file = matches.opt_value_from_str("--log-file")?;
let no_buffering = matches.contains("--no-buffering");
if matches.contains(["-h", "--help"]) { if matches.contains(["-h", "--help"]) {
eprintln!("{}", HELP); eprintln!("{}", HELP);
return Ok(Args { verbosity, log_file: None, command: Command::Help }); return Ok(Args { verbosity, log_file: None, command: Command::Help, no_buffering });
} }
if matches.contains("--print-config-schema") { if matches.contains("--print-config-schema") {
return Ok(Args { verbosity, log_file, command: Command::PrintConfigSchema }); return Ok(Args { verbosity, log_file, command: Command::PrintConfigSchema, no_buffering }, );
} }
let subcommand = match matches.subcommand()? { let subcommand = match matches.subcommand()? {
Some(it) => it, Some(it) => it,
None => { None => {
finish_args(matches)?; finish_args(matches)?;
return Ok(Args { verbosity, log_file, command: Command::RunServer }); return Ok(Args { verbosity, log_file, command: Command::RunServer, no_buffering });
} }
}; };
let command = match subcommand.as_str() { let command = match subcommand.as_str() {
@ -219,11 +223,11 @@ impl Args {
}, },
_ => { _ => {
eprintln!("{}", HELP); eprintln!("{}", HELP);
return Ok(Args { verbosity, log_file: None, command: Command::Help }); return Ok(Args { verbosity, log_file: None, command: Command::Help, no_buffering });
} }
}; };
finish_args(matches)?; finish_args(matches)?;
Ok(Args { verbosity, log_file, command }) Ok(Args { verbosity, log_file, command, no_buffering })
} }
} }

View File

@ -2,10 +2,7 @@
//! filter syntax. Amusingly, there's no crates.io crate that can do this and //! filter syntax. Amusingly, there's no crates.io crate that can do this and
//! only this. //! only this.
use std::{ use std::{borrow::BorrowMut, fs::File, io::{BufWriter, Write}};
fs::File,
io::{BufWriter, Write},
};
use env_logger::filter::{Builder, Filter}; use env_logger::filter::{Builder, Filter};
use log::{Log, Metadata, Record}; use log::{Log, Metadata, Record};
@ -14,10 +11,11 @@ use parking_lot::Mutex;
pub(crate) struct Logger { pub(crate) struct Logger {
filter: Filter, filter: Filter,
file: Option<Mutex<BufWriter<File>>>, file: Option<Mutex<BufWriter<File>>>,
no_buffering: bool,
} }
impl Logger { impl Logger {
pub(crate) fn new(log_file: Option<File>, filter: Option<&str>) -> Logger { pub(crate) fn new(log_file: Option<File>, no_buffering: bool, filter: Option<&str>) -> Logger {
let filter = { let filter = {
let mut builder = Builder::new(); let mut builder = Builder::new();
if let Some(filter) = filter { if let Some(filter) = filter {
@ -28,7 +26,7 @@ impl Logger {
let file = log_file.map(|it| Mutex::new(BufWriter::new(it))); let file = log_file.map(|it| Mutex::new(BufWriter::new(it)));
Logger { filter, file } Logger { filter, file, no_buffering }
} }
pub(crate) fn install(self) { pub(crate) fn install(self) {
@ -55,6 +53,10 @@ impl Log for Logger {
record.module_path().unwrap_or_default(), record.module_path().unwrap_or_default(),
record.args(), record.args(),
); );
if self.no_buffering {
w.lock().borrow_mut().flush().unwrap();
}
} }
None => eprintln!( None => eprintln!(
"[{} {}] {}", "[{} {}] {}",

View File

@ -28,7 +28,7 @@ fn main() {
fn try_main() -> Result<()> { fn try_main() -> Result<()> {
let args = args::Args::parse()?; let args = args::Args::parse()?;
setup_logging(args.log_file)?; setup_logging(args.log_file, args.no_buffering)?;
match args.command { match args.command {
args::Command::RunServer => run_server()?, args::Command::RunServer => run_server()?,
args::Command::PrintConfigSchema => { args::Command::PrintConfigSchema => {
@ -56,7 +56,7 @@ fn try_main() -> Result<()> {
Ok(()) Ok(())
} }
fn setup_logging(log_file: Option<PathBuf>) -> Result<()> { fn setup_logging(log_file: Option<PathBuf>, flush_file: bool) -> Result<()> {
env::set_var("RUST_BACKTRACE", "short"); env::set_var("RUST_BACKTRACE", "short");
let log_file = match log_file { let log_file = match log_file {
@ -69,7 +69,7 @@ fn setup_logging(log_file: Option<PathBuf>) -> Result<()> {
None => None, None => None,
}; };
let filter = env::var("RA_LOG").ok(); let filter = env::var("RA_LOG").ok();
logger::Logger::new(log_file, filter.as_deref()).install(); logger::Logger::new(log_file, flush_file, filter.as_deref()).install();
tracing_setup::setup_tracing()?; tracing_setup::setup_tracing()?;