Skip to content

Commit

Permalink
Merge pull request #74 from drdo/print-log-file
Browse files Browse the repository at this point in the history
Print log file instead of just directory
  • Loading branch information
drdo authored Aug 23, 2024
2 parents 1df54c9 + 4a34421 commit 7323cce
Show file tree
Hide file tree
Showing 6 changed files with 139 additions and 64 deletions.
112 changes: 83 additions & 29 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 3 additions & 3 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -17,14 +17,14 @@ chrono = { version = "0.4", features = ["serde"] }
clap = { version = "4", features = ["derive", "env"] }
crossterm = "0.28"
directories = "5"
flexi_logger = "0.28"
simplelog = "0.12"
humansize = "2"
indicatif = "0.17"
log = "0.4"
rand = "0.8"
ratatui = { version = "0.28", features = [
"unstable-rendered-line-info",
"unstable-widget-ref",
"unstable-rendered-line-info",
"unstable-widget-ref",
] }
rpassword = "7.3.1"
rusqlite = { version = "0.32", features = ["bundled", "functions", "trace"] }
Expand Down
2 changes: 1 addition & 1 deletion src/args.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ pub struct Args {
}

impl Args {
/// Parse arguments from std::env::args_os(), exit on error.
/// Parse arguments from env::args_os(), exit on error.
pub fn parse() -> Self {
let cli = Cli::parse();

Expand Down
6 changes: 4 additions & 2 deletions src/cache/tests.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
use std::{cmp::Reverse, convert::Infallible, fs, iter, mem, path::PathBuf};
use std::{
cmp::Reverse, convert::Infallible, env, fs, iter, mem, path::PathBuf,
};

use camino::{Utf8Path, Utf8PathBuf};
use chrono::{DateTime, NaiveDate, NaiveDateTime, NaiveTime, Utc};
Expand Down Expand Up @@ -39,7 +41,7 @@ impl Drop for Tempfile {

impl Tempfile {
pub fn new() -> Self {
let mut path = std::env::temp_dir();
let mut path = env::temp_dir();
path.push(Uuid::new_v4().to_string());
Tempfile(path)
}
Expand Down
57 changes: 37 additions & 20 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use std::{
fs,
io::stderr,
io::{self, stderr},
sync::{
atomic::{AtomicBool, Ordering},
mpsc::{self, RecvTimeoutError},
Expand All @@ -13,6 +13,7 @@ use std::{
use anyhow::Context;
use args::Args;
use camino::{Utf8Path, Utf8PathBuf};
use chrono::Local;
use crossterm::{
event::{KeyCode, KeyModifiers},
terminal::{
Expand All @@ -22,9 +23,8 @@ use crossterm::{
ExecutableCommand,
};
use directories::ProjectDirs;
use flexi_logger::{FileSpec, Logger, WriteMode};
use indicatif::{MultiProgress, ProgressBar, ProgressStyle};
use log::{error, info, trace};
use log::{debug, error, info, trace, LevelFilter};
use rand::{seq::SliceRandom, thread_rng};
use ratatui::{
backend::{Backend, CrosstermBackend},
Expand All @@ -38,6 +38,7 @@ use redu::{
restic::{self, escape_for_exclude, Restic, Snapshot},
};
use scopeguard::defer;
use simplelog::{ThreadLogMode, WriteLogger};
use thiserror::Error;
use util::snapshot_short_id;

Expand All @@ -54,21 +55,39 @@ fn main() -> anyhow::Result<()> {
let dirs = ProjectDirs::from("eu", "drdo", "redu")
.expect("unable to determine project directory");

let _logger = {
let mut directory = dirs.data_local_dir().to_path_buf();
directory.push(Utf8Path::new("logs"));
// Initialize the logger
{
fn generate_filename() -> String {
format!("{}.log", Local::now().format("%Y-%m-%dT%H:%M:%S%.f%:z"))
}

eprintln!("Logging to {:#?}", directory);
let mut path = dirs.data_local_dir().to_path_buf();
path.push(Utf8Path::new("logs"));
fs::create_dir_all(&path)?;
path.push(generate_filename());
let file = loop {
// Spin until we hit a timestamp that isn't taken yet.
// With the level of precision that we are using this should virtually
// never run more than once.
match fs::OpenOptions::new()
.write(true)
.create_new(true)
.open(&path)
{
Err(err) if err.kind() == io::ErrorKind::AlreadyExists =>
path.set_file_name(generate_filename()),
x => break x,
}
}?;

let filespec =
{ FileSpec::default().directory(directory).suppress_basename() };
eprintln!("Logging to {:#?}", path);

Logger::with(args.log_level)
.log_to_file(filespec)
.write_mode(WriteMode::BufferAndFlush)
.format(flexi_logger::with_thread)
.start()?
};
let config = simplelog::ConfigBuilder::new()
.set_target_level(LevelFilter::Error)
.set_thread_mode(ThreadLogMode::Names)
.build();
WriteLogger::init(args.log_level, config, file)?;
}

unsafe {
rusqlite::trace::config_log(Some(|code, msg| {
Expand Down Expand Up @@ -292,17 +311,15 @@ fn fetching_thread_body(
"snapshot fetched in {}s ({short_id})",
start.elapsed().as_secs_f64()
);
trace!("got snapshot, sending ({short_id})");
if should_quit.load(Ordering::SeqCst) {
return Ok(());
}
let start = Instant::now();
snapshot_sender.send((snapshot.clone(), sizetree)).unwrap();
info!(
debug!(
"waited {}s to send snapshot ({short_id})",
start.elapsed().as_secs_f64()
);
trace!("snapshot sent ({short_id})");
}
Ok(())
}
Expand Down Expand Up @@ -332,7 +349,7 @@ fn db_thread_body(
// We wait with timeout to poll the should_quit periodically
match snapshot_receiver.recv_timeout(should_quit_poll_period) {
Ok((snapshot, sizetree)) => {
info!(
debug!(
"waited {}s to get snapshot",
start.elapsed().as_secs_f64()
);
Expand Down Expand Up @@ -498,7 +515,7 @@ fn ui(mut cache: Cache) -> anyhow::Result<Vec<Utf8PathBuf>> {
fn render<'a>(
terminal: &'a mut Terminal<impl Backend>,
app: &App,
) -> std::io::Result<CompletedFrame<'a>> {
) -> io::Result<CompletedFrame<'a>> {
terminal.draw(|frame| {
let area = frame.area();
let buf = frame.buffer_mut();
Expand Down
Loading

0 comments on commit 7323cce

Please sign in to comment.