Use macros over functions for error logging

This commit is contained in:
Neshura 2024-05-06 20:51:31 +02:00
parent 1cd30b1145
commit 36b59240d9
Signed by: Neshura
GPG key ID: B6983AAA6B9A7A6C
4 changed files with 107 additions and 33 deletions

View file

@ -12,8 +12,34 @@ use std::sync::Arc;
use tokio::sync::RwLock; use tokio::sync::RwLock;
use tokio::time::sleep; use tokio::time::sleep;
use crate::fetchers::Fetcher; use crate::fetchers::Fetcher;
use systemd_journal_logger::connected_to_journal;
pub(crate) async fn run(data: Arc<RwLock<SharedData>>) { macro_rules! info {
($msg:tt) => {
match connected_to_journal() {
true => log::info!("[INFO] {}", $msg),
false => println!("[INFO] {}", $msg),
}
};
}
macro_rules! warn {
($msg:tt) => {
match connected_to_journal() {
true => log::warn!("[WARN] {}", $msg),
false => println!("[WARN] {}", $msg),
}
};
}
macro_rules! error {
($msg:tt) => {
match connected_to_journal() {
true => log::error!("[ERROR] {}", $msg),
false => eprintln!("[ERROR] {}", $msg),
}
};
}
let mut last_reload: DateTime<Utc>; let mut last_reload: DateTime<Utc>;
let mut lemmy: Lemmy; let mut lemmy: Lemmy;
let mut login_error: bool; let mut login_error: bool;
@ -47,7 +73,7 @@ pub(crate) async fn run(data: Arc<RwLock<SharedData>>) {
} }
let info_msg = "Bot init successful, starting normal operations".to_owned(); let info_msg = "Bot init successful, starting normal operations".to_owned();
write_info(info_msg); info!(info_msg);
loop { loop {
idle(&data).await; idle(&data).await;
@ -56,8 +82,8 @@ pub(crate) async fn run(data: Arc<RwLock<SharedData>>) {
let mut write = data.write().await; let mut write = data.write().await;
write.start = Utc::now(); write.start = Utc::now();
let message = "Config reloaded".to_owned();
if write.start - last_reload >= Duration::seconds(write.config.config_reload_seconds as i64) { info!(message);
write.config = Config::load(); write.config = Config::load();
let message = "Config reloaded".to_owned(); let message = "Config reloaded".to_owned();
write_info(message); write_info(message);
@ -65,9 +91,9 @@ pub(crate) async fn run(data: Arc<RwLock<SharedData>>) {
} }
{ {
let read = data.read().await; let info_msg = "Login invalid, refreshing session";
if login_error { info!(info_msg);
lemmy = match lemmy::login(&read.config).await { lemmy = match lemmy::login(&config).await {
Ok(data) => data, Ok(data) => data,
Err(_) => continue, Err(_) => continue,
}; };
@ -83,9 +109,9 @@ pub(crate) async fn run(data: Arc<RwLock<SharedData>>) {
Err(_) => { Err(_) => {
login_error = true; login_error = true;
continue; continue;
}
};
let message = "Communities reloaded".to_owned(); let message = "Communities reloaded".to_owned();
info!(message);
last_reload = Utc::now();
write_info(message); write_info(message);
last_reload = Utc::now(); last_reload = Utc::now();
} }
@ -127,7 +153,7 @@ async fn idle(data: &Arc<RwLock<SharedData>>) {
Ok(_) => {} Ok(_) => {}
Err(e) => { Err(e) => {
let err_msg = format!("{e}"); let err_msg = format!("{e}");
write_error(err_msg); error!(err_msg);
} }
} }
}; };
@ -144,6 +170,11 @@ async fn handle_series(series: &SeriesConfig, communities: &HashMap<String, Comm
Err(_) => return Err(()), Err(_) => return Err(()),
}; };
if post_list.is_empty() && Utc::now().minute() % 10 == 0 {
let info_msg = "No Updates found";
info!(info_msg);
}
for post_info in post_list.clone().iter() { for post_info in post_list.clone().iter() {
// todo .clone() likely not needed // todo .clone() likely not needed
let post_part_info = post_info.get_part_info(); let post_part_info = post_info.get_part_info();
@ -190,7 +221,7 @@ async fn handle_series(series: &SeriesConfig, communities: &HashMap<String, Comm
post_lemmy_info.title.as_str(), post_lemmy_info.title.as_str(),
post_series_config.name.as_str() post_series_config.name.as_str()
); );
write_info(info); info!(info);
let post_id = lemmy.post(post_data).await?; let post_id = lemmy.post(post_data).await?;
{ {
@ -199,7 +230,7 @@ async fn handle_series(series: &SeriesConfig, communities: &HashMap<String, Comm
&& !read && !read
.config .config
.protected_communities .protected_communities
.contains(&post_series_config.name) info!(info);
{ {
let info = format!( let info = format!(
"Pinning '{}' to {}", "Pinning '{}' to {}",
@ -226,12 +257,13 @@ async fn handle_series(series: &SeriesConfig, communities: &HashMap<String, Comm
); );
write_warn(message); write_warn(message);
} }
warn!(message);
} }
let read = data.read().await; let read = data.read().await;
if post_series_config.pin_settings.pin_new_post_local { if post_series_config.pin_settings.pin_new_post_local {
let info = format!("Pinning '{}' to Instance", post_lemmy_info.title); let info = format!("Pinning '{}' to Instance", post_lemmy_info.title);
write_info(info); info!(info);
let pinned_posts = lemmy.get_local_pinned().await?; let pinned_posts = lemmy.get_local_pinned().await?;
if !pinned_posts.is_empty() { if !pinned_posts.is_empty() {
for pinned_post in pinned_posts { for pinned_post in pinned_posts {

View file

@ -1,4 +1,4 @@
use crate::{write_error, HTTP_CLIENT, lemmy}; use crate::{HTTP_CLIENT, lemmy};
use chrono::{DateTime, Duration, Utc}; use chrono::{DateTime, Duration, Utc};
use serde_derive::{Deserialize, Serialize}; use serde_derive::{Deserialize, Serialize};
use std::cmp::Ordering; use std::cmp::Ordering;
@ -10,6 +10,16 @@ use crate::fetchers::Fetcher;
use crate::fetchers::jnovel::JPostInfo::{Chapter, Volume}; use crate::fetchers::jnovel::JPostInfo::{Chapter, Volume};
use crate::fetchers::jnovel::PartInfo::{NoParts, Part}; use crate::fetchers::jnovel::PartInfo::{NoParts, Part};
use crate::lemmy::{PostInfo, PostInfoInner}; use crate::lemmy::{PostInfo, PostInfoInner};
use systemd_journal_logger::connected_to_journal;
macro_rules! error {
($msg:tt) => {
match connected_to_journal() {
true => log::error!("[ERROR] {}", $msg),
false => eprintln!("[ERROR] {}", $msg),
}
};
}
static PAST_DAYS_ELIGIBLE: u8 = 4; static PAST_DAYS_ELIGIBLE: u8 = 4;
@ -266,13 +276,13 @@ impl Fetcher for JFetcherOptions {
Ok(data) => data, Ok(data) => data,
Err(e) => { Err(e) => {
let err_msg = format!("{e}"); let err_msg = format!("{e}");
write_error(err_msg); error!(err_msg);
return Err(()); return Err(());
} }
}, },
Err(e) => { Err(e) => {
let err_msg = format!("{e}"); let err_msg = format!("{e}");
write_error(err_msg); error!(err_msg);
return Err(()); return Err(());
} }
}; };
@ -281,7 +291,7 @@ impl Fetcher for JFetcherOptions {
Ok(data) => data, Ok(data) => data,
Err(e) => { Err(e) => {
let err_msg = format!("{e}"); let err_msg = format!("{e}");
write_error(err_msg); error!(err_msg);
return Err(()); return Err(());
} }
}; };
@ -392,13 +402,13 @@ async fn get_latest_prepub(volume_slug: &str) -> Result<Option<lemmy::PostInfoIn
Ok(data) => data, Ok(data) => data,
Err(e) => { Err(e) => {
let err_msg = format!("{e}"); let err_msg = format!("{e}");
write_error(err_msg); error!(err_msg);
return Err(()); return Err(());
} }
}, },
Err(e) => { Err(e) => {
let err_msg = format!("{e}"); let err_msg = format!("{e}");
write_error(err_msg); error!(err_msg);
return Err(()); return Err(());
} }
}; };
@ -407,7 +417,7 @@ async fn get_latest_prepub(volume_slug: &str) -> Result<Option<lemmy::PostInfoIn
Ok(data) => data, Ok(data) => data,
Err(e) => { Err(e) => {
let err_msg = format!("{e}"); let err_msg = format!("{e}");
write_error(err_msg); error!(err_msg);
return Err(()); return Err(());
} }
}; };

View file

@ -1,5 +1,5 @@
use crate::config::Config; use crate::config::Config;
use crate::{write_error, HTTP_CLIENT}; use crate::{HTTP_CLIENT};
use lemmy_api_common::community::{ListCommunities, ListCommunitiesResponse}; use lemmy_api_common::community::{ListCommunities, ListCommunitiesResponse};
use lemmy_api_common::lemmy_db_views::structs::PostView; use lemmy_api_common::lemmy_db_views::structs::PostView;
use lemmy_api_common::person::{Login, LoginResponse}; use lemmy_api_common::person::{Login, LoginResponse};
@ -10,6 +10,16 @@ use lemmy_db_schema::{ListingType, PostFeatureType};
use reqwest::StatusCode; use reqwest::StatusCode;
use std::collections::HashMap; use std::collections::HashMap;
use url::Url; use url::Url;
use systemd_journal_logger::connected_to_journal;
macro_rules! error {
($msg:tt) => {
match connected_to_journal() {
true => log::error!("[ERROR] {}", $msg),
false => eprintln!("[ERROR] {}", $msg),
}
};
}
pub(crate) struct Lemmy { pub(crate) struct Lemmy {
jwt_token: Sensitive<String>, jwt_token: Sensitive<String>,
@ -45,7 +55,7 @@ pub(crate) async fn login(config: &Config) -> Result<Lemmy, ()> {
Ok(data) => data, Ok(data) => data,
Err(e) => { Err(e) => {
let err_msg = format!("{e}"); let err_msg = format!("{e}");
write_error(err_msg); error!(err_msg);
return Err(()); return Err(());
} }
}; };
@ -63,14 +73,14 @@ pub(crate) async fn login(config: &Config) -> Result<Lemmy, ()> {
}), }),
None => { None => {
let err_msg = "Login did not return JWT token. Are the credentials valid?".to_owned(); let err_msg = "Login did not return JWT token. Are the credentials valid?".to_owned();
write_error(err_msg); error!(err_msg);
Err(()) Err(())
} }
} }
} }
status => { status => {
let err_msg = format!("Unexpected HTTP Status '{}' during Login", status); let err_msg = format!("Unexpected HTTP Status '{}' during Login", status);
write_error(err_msg); error!(err_msg);
Err(()) Err(())
} }
} }
@ -273,14 +283,14 @@ impl Lemmy {
Ok(data) => data, Ok(data) => data,
Err(e) => { Err(e) => {
let err_msg = format!("{e}"); let err_msg = format!("{e}");
write_error(err_msg); error!(err_msg);
return Err(()); Err(())
} }
}, },
Err(e) => { Err(e) => {
let err_msg = format!("{e}"); let err_msg = format!("{e}");
write_error(err_msg); error!(err_msg);
return Err(()); Err(())
} }
}; };
@ -288,8 +298,8 @@ impl Lemmy {
Ok(data) => data, Ok(data) => data,
Err(e) => { Err(e) => {
let err_msg = format!("{e}"); let err_msg = format!("{e}");
write_error(err_msg); error!(err_msg);
return Err(()); Err(())
} }
}; };

View file

@ -1,6 +1,24 @@
use crate::write_error;
use serde_derive::{Deserialize, Serialize}; use serde_derive::{Deserialize, Serialize};
use std::collections::HashMap; use std::collections::HashMap;
use systemd_journal_logger::connected_to_journal;
macro_rules! info {
($msg:tt) => {
match connected_to_journal() {
true => log::info!("[INFO] {}", $msg),
false => println!("[INFO] {}", $msg),
}
};
}
macro_rules! error {
($msg:tt) => {
match connected_to_journal() {
true => log::error!("[ERROR] {}", $msg),
false => eprintln!("[ERROR] {}", $msg),
}
};
}
#[derive(Serialize, Deserialize, Default, Clone, Debug)] #[derive(Serialize, Deserialize, Default, Clone, Debug)]
pub(crate) struct SeriesHistory { pub(crate) struct SeriesHistory {
@ -9,6 +27,8 @@ pub(crate) struct SeriesHistory {
impl SeriesHistory { impl SeriesHistory {
pub(crate) fn load_history() -> Self { pub(crate) fn load_history() -> Self {
let info_msg = "Loading History";
info!(info_msg);
match confy::load(env!("CARGO_PKG_NAME"), "history") { match confy::load(env!("CARGO_PKG_NAME"), "history") {
Ok(data) => data, Ok(data) => data,
Err(e) => panic!("history.toml not found: {e}"), Err(e) => panic!("history.toml not found: {e}"),
@ -16,9 +36,11 @@ impl SeriesHistory {
} }
pub(crate) fn save_history(&self) { pub(crate) fn save_history(&self) {
let info_msg = "Saving History";
info!(info_msg);
if let Err(e) = confy::store(env!("CARGO_PKG_NAME"), "history", self) { if let Err(e) = confy::store(env!("CARGO_PKG_NAME"), "history", self) {
let err_msg = format!("Unexpected error saving to history.toml: {e}"); let err_msg = format!("Unexpected error saving to history.toml: {e}");
write_error(err_msg); error!(err_msg);
} }
} }