diff options
author | Christian Duerr <chrisduerr@users.noreply.github.com> | 2018-11-17 14:39:13 +0000 |
---|---|---|
committer | GitHub <noreply@github.com> | 2018-11-17 14:39:13 +0000 |
commit | 6265ef91d5496461fcd1025b21323982f3e47085 (patch) | |
tree | d8ab17aac3c2833d5bb231a5346504c227a242f1 /src/logging.rs | |
parent | ea637cde1c82ad971078671aff087236f3fb0fbd (diff) | |
download | alacritty-6265ef91d5496461fcd1025b21323982f3e47085.tar.gz alacritty-6265ef91d5496461fcd1025b21323982f3e47085.zip |
Display errors and warnings
To make sure that all error and information reporting to the user is
unified, all instances of `print!`, `eprint!`, `println!` and
`eprintln!` have been removed and replaced by logging.
When `RUST_LOG` is not specified, the default Alacritty logger now also
prints to both the stderr and a log file. The log file is only created
when a message is written to it and its name is printed to stdout the
first time it is used.
Whenever a warning or an error has been written to the log file/stderr,
a message is now displayed in Alacritty which points to the log file
where the full error is documented.
The message is cleared whenever the screen is cleared using either the
`clear` command or the `Ctrl+L` key binding.
To make sure that log files created by root don't prevent normal users
from interacting with them, the Alacritty log file is `/tmp/Alacritty-$PID.log`.
Since it's still possible that the log file can't be created, the UI
error/warning message now informs the user if the message was only
written to stderr. The reason why it couldn't be created is then printed
to stderr.
To make sure the deletion of the log file at runtime doesn't create any
issues, the file is re-created if a write is attempted without the file
being present.
To help with debugging Alacritty issues, a timestamp and the error
level are printed in all log messages.
All log messages now follow this format:
[YYYY-MM-DD HH:MM] [LEVEL] Message
Since it's not unusual to spawn a lot of different terminal emulators
without restarting, Alacritty can create a ton of different log files.
To combat this problem, logfiles are removed by default after
Alacritty has been closed. If the user wants to persist the log of a
single session, the `--persistent_logging` option can be used. For
persisting all log files, the `persistent_logging` option can be set in
the configuration file
Diffstat (limited to 'src/logging.rs')
-rw-r--r-- | src/logging.rs | 203 |
1 files changed, 185 insertions, 18 deletions
diff --git a/src/logging.rs b/src/logging.rs index 10929980..5ad1dcd5 100644 --- a/src/logging.rs +++ b/src/logging.rs @@ -17,37 +17,134 @@ //! The main executable is supposed to call `initialize()` exactly once during //! startup. All logging messages are written to stdout, given that their //! log-level is sufficient for the level configured in `cli::Options`. -use log; -use std::sync; -use std::io; use cli; +use log::{self, Level}; +use time; -pub struct Logger<T> { +use std::env; +use std::fs::{self, File, OpenOptions}; +use std::io::{self, LineWriter, Stdout, Write}; +use std::path::PathBuf; +use std::process; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Arc, Mutex}; + +pub fn initialize(options: &cli::Options) -> Result<LoggerProxy, log::SetLoggerError> { + // Use env_logger if RUST_LOG environment variable is defined. Otherwise, + // use the alacritty-only logger. + if ::std::env::var("RUST_LOG").is_ok() { + ::env_logger::try_init()?; + Ok(LoggerProxy::default()) + } else { + let logger = Logger::new(options.log_level); + let proxy = logger.proxy(); + + log::set_boxed_logger(Box::new(logger))?; + + Ok(proxy) + } +} + +/// Proxy object for bidirectional communicating with the global logger. +#[derive(Clone, Default)] +pub struct LoggerProxy { + errors: Arc<AtomicBool>, + warnings: Arc<AtomicBool>, + logfile_proxy: OnDemandLogFileProxy, +} + +impl LoggerProxy { + /// Check for new logged errors. + pub fn errors(&self) -> bool { + self.errors.load(Ordering::Relaxed) + } + + /// Check for new logged warnings. + pub fn warnings(&self) -> bool { + self.warnings.load(Ordering::Relaxed) + } + + /// Get the path of the log file if it has been created. + pub fn log_path(&self) -> Option<&str> { + if self.logfile_proxy.created.load(Ordering::Relaxed) { + Some(&self.logfile_proxy.path) + } else { + None + } + } + + /// Clear log warnings/errors from the Alacritty UI. + pub fn clear(&mut self) { + self.errors.store(false, Ordering::Relaxed); + self.warnings.store(false, Ordering::Relaxed); + } + + pub fn delete_log(&mut self) { + self.logfile_proxy.delete_log(); + } +} + +struct Logger { level: log::LevelFilter, - output: sync::Mutex<T> + logfile: Mutex<OnDemandLogFile>, + stdout: Mutex<LineWriter<Stdout>>, + errors: Arc<AtomicBool>, + warnings: Arc<AtomicBool>, } -impl<T: Send + io::Write> Logger<T> { +impl Logger { // False positive, see: https://github.com/rust-lang-nursery/rust-clippy/issues/734 #[cfg_attr(feature = "cargo-clippy", allow(new_ret_no_self))] - pub fn new(output: T, level: log::LevelFilter) -> Logger<io::LineWriter<T>> { + fn new(level: log::LevelFilter) -> Self { log::set_max_level(level); + + let logfile = Mutex::new(OnDemandLogFile::new()); + let stdout = Mutex::new(LineWriter::new(io::stdout())); + Logger { level, - output: sync::Mutex::new(io::LineWriter::new(output)) + logfile, + stdout, + errors: Arc::new(AtomicBool::new(false)), + warnings: Arc::new(AtomicBool::new(false)), + } + } + + fn proxy(&self) -> LoggerProxy { + LoggerProxy { + errors: self.errors.clone(), + warnings: self.warnings.clone(), + logfile_proxy: self.logfile.lock().expect("").proxy(), } } } -impl<T: Send + io::Write> log::Log for Logger<T> { +impl log::Log for Logger { fn enabled(&self, metadata: &log::Metadata) -> bool { metadata.level() <= self.level } fn log(&self, record: &log::Record) { if self.enabled(record.metadata()) && record.target().starts_with("alacritty") { - if let Ok(ref mut writer) = self.output.lock() { - let _ = writer.write_all(format!("{}\n", record.args()).as_ref()); + let msg = format!( + "[{}] [{}] {}\n", + time::now().strftime("%F %R").unwrap(), + record.level(), + record.args() + ); + + if let Ok(ref mut logfile) = self.logfile.lock() { + let _ = logfile.write_all(msg.as_ref()); + } + + if let Ok(ref mut stdout) = self.stdout.lock() { + let _ = stdout.write_all(msg.as_ref()); + } + + match record.level() { + Level::Error => self.errors.store(true, Ordering::Relaxed), + Level::Warn => self.warnings.store(true, Ordering::Relaxed), + _ => (), } } } @@ -55,12 +152,82 @@ impl<T: Send + io::Write> log::Log for Logger<T> { fn flush(&self) {} } -pub fn initialize(options: &cli::Options) -> Result<(), log::SetLoggerError> { - // Use env_logger if RUST_LOG environment variable is defined. Otherwise, - // use the alacritty-only logger. - if ::std::env::var("RUST_LOG").is_ok() { - ::env_logger::try_init() - } else { - log::set_boxed_logger(Box::new(Logger::new(io::stdout(), options.log_level))) +#[derive(Clone, Default)] +struct OnDemandLogFileProxy { + created: Arc<AtomicBool>, + path: String, +} + +impl OnDemandLogFileProxy { + fn delete_log(&mut self) { + if self.created.load(Ordering::Relaxed) && fs::remove_file(&self.path).is_ok() { + let _ = writeln!(io::stdout(), "Deleted log file at {:?}", self.path); + self.created.store(false, Ordering::Relaxed); + } + } +} + +struct OnDemandLogFile { + file: Option<LineWriter<File>>, + created: Arc<AtomicBool>, + path: PathBuf, +} + +impl OnDemandLogFile { + fn new() -> Self { + let mut path = env::temp_dir(); + path.push(format!("Alacritty-{}.log", process::id())); + + OnDemandLogFile { + path, + file: None, + created: Arc::new(AtomicBool::new(false)), + } + } + + fn file(&mut self) -> Result<&mut LineWriter<File>, io::Error> { + // Allow to recreate the file if it has been deleted at runtime + if self.file.is_some() && !self.path.as_path().exists() { + self.file = None; + } + + // Create the file if it doesn't exist yet + if self.file.is_none() { + let file = OpenOptions::new() + .append(true) + .create(true) + .open(&self.path); + + match file { + Ok(file) => { + self.file = Some(io::LineWriter::new(file)); + self.created.store(true, Ordering::Relaxed); + let _ = writeln!(io::stdout(), "Created log file at {:?}", self.path); + } + Err(e) => { + let _ = writeln!(io::stdout(), "Unable to create log file: {}", e); + return Err(e); + } + } + } + + Ok(self.file.as_mut().unwrap()) + } + + fn proxy(&self) -> OnDemandLogFileProxy { + OnDemandLogFileProxy { + created: self.created.clone(), + path: self.path.to_string_lossy().to_string(), + } + } +} + +impl Write for OnDemandLogFile { + fn write(&mut self, buf: &[u8]) -> Result<usize, io::Error> { + self.file()?.write(buf) + } + + fn flush(&mut self) -> Result<(), io::Error> { + self.file()?.flush() } } |