diff --git a/lighthouse/environment/src/lib.rs b/lighthouse/environment/src/lib.rs index 06ade157c2..cba77a03fe 100644 --- a/lighthouse/environment/src/lib.rs +++ b/lighthouse/environment/src/lib.rs @@ -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 Environment { /// 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)