Create backup instead of overwriting log files (#686)
* Create backup instead of overwriting log files * Clean variable names * Return string instead of expect on SystemTimeError * Cargo fmt after merge
This commit is contained in:
parent
b1d4284524
commit
0694d1d0ec
@ -12,9 +12,11 @@ use futures::{sync::oneshot, Future};
|
||||
use slog::{info, o, Drain, Level, Logger};
|
||||
use sloggers::{null::NullLoggerBuilder, Build};
|
||||
use std::cell::RefCell;
|
||||
use std::fs::OpenOptions;
|
||||
use std::ffi::OsStr;
|
||||
use std::fs::{rename as FsRename, OpenOptions};
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Mutex;
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
use tokio::runtime::{Builder as RuntimeBuilder, Runtime, TaskExecutor};
|
||||
use types::{EthSpec, InteropEthSpec, MainnetEthSpec, MinimalEthSpec};
|
||||
|
||||
@ -229,6 +231,24 @@ impl<E: EthSpec> Environment<E> {
|
||||
|
||||
/// Sets the logger (and all child loggers) to log to a file.
|
||||
pub fn log_to_json_file(&mut self, path: PathBuf, debug_level: &str) -> Result<(), String> {
|
||||
// Creating a backup if the logfile already exists.
|
||||
if path.exists() {
|
||||
let start = SystemTime::now();
|
||||
let timestamp = start
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.map_err(|e| e.to_string())?
|
||||
.as_secs();
|
||||
let file_stem = path
|
||||
.file_stem()
|
||||
.ok_or_else(|| "Invalid file name".to_string())?
|
||||
.to_str()
|
||||
.ok_or_else(|| "Failed to create str from filename".to_string())?;
|
||||
let file_ext = path.extension().unwrap_or_else(|| OsStr::new(""));
|
||||
let backup_name = format!("{}_backup_{}", file_stem, timestamp);
|
||||
let backup_path = path.with_file_name(backup_name).with_extension(file_ext);
|
||||
FsRename(&path, &backup_path).map_err(|e| e.to_string())?;
|
||||
}
|
||||
|
||||
let file = OpenOptions::new()
|
||||
.create(true)
|
||||
.write(true)
|
||||
|
Loading…
Reference in New Issue
Block a user