2020-04-17 12:11:25 +00:00
|
|
|
use anyhow::{Error};
|
2019-04-03 06:58:43 +00:00
|
|
|
use chrono::{TimeZone, Local};
|
2019-03-01 08:34:29 +00:00
|
|
|
use std::io::Write;
|
|
|
|
|
|
|
|
/// Log messages with timestamps into files
|
|
|
|
///
|
|
|
|
/// Logs messages to file, and optionaly to standart output.
|
|
|
|
///
|
|
|
|
///
|
|
|
|
/// #### Example:
|
|
|
|
/// ```
|
|
|
|
/// #[macro_use] extern crate proxmox_backup;
|
2020-04-17 12:11:25 +00:00
|
|
|
/// # use anyhow::{bail, format_err, Error};
|
2019-03-01 08:34:29 +00:00
|
|
|
/// use proxmox_backup::tools::FileLogger;
|
|
|
|
///
|
2019-04-06 09:24:37 +00:00
|
|
|
/// # std::fs::remove_file("test.log");
|
2019-03-01 08:34:29 +00:00
|
|
|
/// let mut log = FileLogger::new("test.log", true).unwrap();
|
|
|
|
/// flog!(log, "A simple log: {}", "Hello!");
|
|
|
|
/// ```
|
|
|
|
|
|
|
|
|
2019-04-03 06:58:43 +00:00
|
|
|
#[derive(Debug)]
|
2019-03-01 08:34:29 +00:00
|
|
|
pub struct FileLogger {
|
|
|
|
file: std::fs::File,
|
|
|
|
to_stdout: bool,
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Log messages to [FileLogger](tools/struct.FileLogger.html)
|
|
|
|
#[macro_export]
|
|
|
|
macro_rules! flog {
|
|
|
|
($log:expr, $($arg:tt)*) => ({
|
|
|
|
$log.log(format!($($arg)*));
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
impl FileLogger {
|
|
|
|
|
2019-04-03 12:13:33 +00:00
|
|
|
pub fn new<P: AsRef<std::path::Path>>(file_name: P, to_stdout: bool) -> Result<Self, Error> {
|
2019-03-01 08:34:29 +00:00
|
|
|
|
|
|
|
let file = std::fs::OpenOptions::new()
|
|
|
|
.read(true)
|
|
|
|
.write(true)
|
|
|
|
.create_new(true)
|
|
|
|
.open(file_name)?;
|
|
|
|
|
|
|
|
Ok(Self { file , to_stdout })
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn log<S: AsRef<str>>(&mut self, msg: S) {
|
|
|
|
|
|
|
|
let msg = msg.as_ref();
|
|
|
|
|
|
|
|
let mut stdout = std::io::stdout();
|
|
|
|
if self.to_stdout {
|
2019-09-11 11:56:09 +00:00
|
|
|
stdout.write_all(msg.as_bytes()).unwrap();
|
|
|
|
stdout.write_all(b"\n").unwrap();
|
2019-03-01 08:34:29 +00:00
|
|
|
}
|
|
|
|
|
2019-04-03 06:58:43 +00:00
|
|
|
let line = format!("{}: {}\n", Local.timestamp(Local::now().timestamp(), 0).to_rfc3339(), msg);
|
2019-09-11 11:56:09 +00:00
|
|
|
self.file.write_all(line.as_bytes()).unwrap();
|
2019-03-01 08:34:29 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl std::io::Write for FileLogger {
|
|
|
|
fn write(&mut self, buf: &[u8]) -> Result<usize, std::io::Error> {
|
|
|
|
if self.to_stdout { let _ = std::io::stdout().write(buf); }
|
|
|
|
self.file.write(buf)
|
|
|
|
}
|
|
|
|
|
|
|
|
fn flush(&mut self) -> Result<(), std::io::Error> {
|
|
|
|
if self.to_stdout { let _ = std::io::stdout().flush(); }
|
|
|
|
self.file.flush()
|
|
|
|
}
|
|
|
|
}
|