1use crate::{
2 exists,
3 write_string,
4 FileError,
5 WriteMode,
6};
7use chrono::offset::Local;
8
9static mut LOG_FILE_PATH: Option<[u8; 1024]> = None;
10static mut LOG_FILE_PATH_LEN: usize = 0;
11
12pub fn set_log_file_path(path: Option<String>) {
13 unsafe {
14 if let Some(path) = path {
15 let mut bytes = [0; 1024];
16
17 for (i, c) in path.as_bytes().iter().enumerate() {
18 bytes[i] = *c;
19 }
20
21 LOG_FILE_PATH_LEN = path.len();
22 LOG_FILE_PATH = Some(bytes);
23 }
24
25 else {
26 LOG_FILE_PATH = None;
27 }
28 }
29}
30
31fn get_log_file_path() -> Option<String> {
32 unsafe {
33 LOG_FILE_PATH.map(|bytes| String::from_utf8_lossy(&bytes[..LOG_FILE_PATH_LEN]).to_string())
34 }
35}
36
37pub fn initialize_log_file(path: &str, remove_existing_file: bool) -> Result<(), FileError> {
38 if remove_existing_file {
39 if exists(path) {
40 if let Err(e) = std::fs::copy(
42 path,
43 &format!("{path}-backup"),
44 ) {
45 return Err(FileError::from_std(e, path)); }
47 }
48
49 write_string(path, "", WriteMode::Atomic)?;
50 }
51
52 Ok(())
53}
54
55pub fn write_log(owner: &str, msg: &str) {
56 if let Some(path) = get_log_file_path() {
57 write_string(
58 &path,
59 &format!(
60 "{} | {} | {msg}\n",
61 Local::now().to_rfc2822(),
62 if owner.len() < 32 {
63 format!("{}{owner}", " ".repeat(32 - owner.len()))
64 } else {
65 owner.to_string()
66 },
67 ),
68 WriteMode::AlwaysAppend,
69 ).unwrap();
70 }
71}