summaryrefslogtreecommitdiffstats
path: root/src/log.rs
diff options
context:
space:
mode:
authorqkzk <qu3nt1n@gmail.com>2023-09-20 22:19:59 +0200
committerqkzk <qu3nt1n@gmail.com>2023-09-20 22:19:59 +0200
commit53adf97bfda0060010ccdf0f8d2ef18bfe015de2 (patch)
treea350a7b54771a728e078e495b1359cf0dc2e3c1b /src/log.rs
parent67217f4485f4aa28b485b1e0b2c68cb669504ebc (diff)
don't display log line for events more than 24h ago
Diffstat (limited to 'src/log.rs')
-rw-r--r--src/log.rs32
1 files changed, 32 insertions, 0 deletions
diff --git a/src/log.rs b/src/log.rs
index a5a9518..b86eecf 100644
--- a/src/log.rs
+++ b/src/log.rs
@@ -1,9 +1,12 @@
use anyhow::Result;
+use chrono::{offset, LocalResult, NaiveDateTime, Utc};
use log4rs;
use crate::constant_strings_paths::{ACTION_LOG_PATH, LOG_CONFIG_PATH};
use crate::utils::extract_lines;
+const ONE_DAY_IN_SECONDS: i64 = 24 * 60 * 60;
+
/// Set the logs.
/// The configuration is read from a config file defined in `LOG_CONFIG_PATH`
/// It's a YAML file which defines 2 logs:
@@ -23,3 +26,32 @@ pub fn read_log() -> Result<Vec<String>> {
let content = std::fs::read_to_string(log_path)?;
Ok(extract_lines(content))
}
+
+/// Parse log line, reads its date and compare it to Utc now.
+/// True, If the date is readable and less than a day ago.
+pub fn is_log_recent_engough(line: &str) -> Result<bool> {
+ let strings: Vec<&str> = line.split(" - ").collect();
+ if strings.is_empty() {
+ Ok(false)
+ } else {
+ Ok(is_recent_enough(to_naive_datetime(strings[0])?))
+ }
+}
+
+/// Parse a string like "2023-09-19 20:44:22" to a `chrono::NaiveDateTime`.
+fn to_naive_datetime(str_date: &str) -> Result<NaiveDateTime> {
+ Ok(NaiveDateTime::parse_from_str(
+ str_date,
+ "%Y-%m-%d %H:%M:%S",
+ )?)
+}
+
+/// True iff the datetime can be parsed to Utc and is less than a day ago.
+fn is_recent_enough(dt_naive: NaiveDateTime) -> bool {
+ if let LocalResult::Single(dt_utc) = dt_naive.and_local_timezone(offset::Local) {
+ let delta = Utc::now().timestamp() - dt_utc.timestamp();
+ delta < ONE_DAY_IN_SECONDS
+ } else {
+ false
+ }
+}