Add function to report devices activity

This commit is contained in:
2024-09-30 22:11:48 +02:00
parent 5608b4e610
commit 63bdeed952
17 changed files with 266 additions and 79 deletions

View File

@ -0,0 +1,17 @@
use crate::devices::device::DeviceId;
use crate::logs::severity::LogSeverity;
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone)]
pub struct LogEntry {
/// If no device is specified then the message comes from the backend
pub device_id: Option<DeviceId>,
pub time: u64,
pub severity: LogSeverity,
pub message: String,
}
impl LogEntry {
pub fn serialize(&self) -> anyhow::Result<String> {
Ok(serde_json::to_string(self)?)
}
}

View File

@ -0,0 +1,41 @@
use crate::app_config::AppConfig;
use crate::devices::device::DeviceId;
use crate::logs::log_entry::LogEntry;
use crate::logs::severity::LogSeverity;
use crate::utils::time_utils::{curr_day_number, time_secs};
use fs4::fs_std::FileExt;
use std::fs::OpenOptions;
use std::io::{Seek, SeekFrom, Write};
pub fn save_log(
device: Option<&DeviceId>,
severity: LogSeverity,
message: String,
) -> anyhow::Result<()> {
let log_path = AppConfig::get().log_of_day(curr_day_number());
let mut file = OpenOptions::new()
.append(true)
.create(true)
.open(&log_path)?;
file.lock_exclusive()?;
file.seek(SeekFrom::End(0))?;
file.write_all(
format!(
"{}\n",
(LogEntry {
device_id: device.cloned(),
time: time_secs(),
severity,
message,
})
.serialize()?
)
.as_bytes(),
)?;
file.flush()?;
file.unlock()?;
Ok(())
}

View File

@ -0,0 +1,3 @@
pub mod log_entry;
pub mod logs_manager;
pub mod severity;

View File

@ -0,0 +1,7 @@
#[derive(serde::Serialize, serde::Deserialize, Copy, Clone, Debug)]
pub enum LogSeverity {
Debug,
Info,
Warn,
Error,
}