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::time::sleep;
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 lemmy: Lemmy;
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();
write_info(info_msg);
info!(info_msg);
loop {
idle(&data).await;
@ -56,8 +82,8 @@ pub(crate) async fn run(data: Arc<RwLock<SharedData>>) {
let mut write = data.write().await;
write.start = Utc::now();
if write.start - last_reload >= Duration::seconds(write.config.config_reload_seconds as i64) {
let message = "Config reloaded".to_owned();
info!(message);
write.config = Config::load();
let message = "Config reloaded".to_owned();
write_info(message);
@ -65,9 +91,9 @@ pub(crate) async fn run(data: Arc<RwLock<SharedData>>) {
}
{
let read = data.read().await;
if login_error {
lemmy = match lemmy::login(&read.config).await {
let info_msg = "Login invalid, refreshing session";
info!(info_msg);
lemmy = match lemmy::login(&config).await {
Ok(data) => data,
Err(_) => continue,
};
@ -83,9 +109,9 @@ pub(crate) async fn run(data: Arc<RwLock<SharedData>>) {
Err(_) => {
login_error = true;
continue;
}
};
let message = "Communities reloaded".to_owned();
let message = "Communities reloaded".to_owned();
info!(message);
last_reload = Utc::now();
write_info(message);
last_reload = Utc::now();
}
@ -127,7 +153,7 @@ async fn idle(data: &Arc<RwLock<SharedData>>) {
Ok(_) => {}
Err(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(()),
};
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() {
// todo .clone() likely not needed
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_series_config.name.as_str()
);
write_info(info);
info!(info);
let post_id = lemmy.post(post_data).await?;
{
@ -199,7 +230,7 @@ async fn handle_series(series: &SeriesConfig, communities: &HashMap<String, Comm
&& !read
.config
.protected_communities
.contains(&post_series_config.name)
info!(info);
{
let info = format!(
"Pinning '{}' to {}",
@ -226,12 +257,13 @@ async fn handle_series(series: &SeriesConfig, communities: &HashMap<String, Comm
);
write_warn(message);
}
warn!(message);
}
let read = data.read().await;
if post_series_config.pin_settings.pin_new_post_local {
let info = format!("Pinning '{}' to Instance", post_lemmy_info.title);
write_info(info);
info!(info);
let pinned_posts = lemmy.get_local_pinned().await?;
if !pinned_posts.is_empty() {
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 serde_derive::{Deserialize, Serialize};
use std::cmp::Ordering;
@ -10,6 +10,16 @@ use crate::fetchers::Fetcher;
use crate::fetchers::jnovel::JPostInfo::{Chapter, Volume};
use crate::fetchers::jnovel::PartInfo::{NoParts, Part};
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;
@ -266,13 +276,13 @@ impl Fetcher for JFetcherOptions {
Ok(data) => data,
Err(e) => {
let err_msg = format!("{e}");
write_error(err_msg);
error!(err_msg);
return Err(());
}
},
Err(e) => {
let err_msg = format!("{e}");
write_error(err_msg);
error!(err_msg);
return Err(());
}
};
@ -281,7 +291,7 @@ impl Fetcher for JFetcherOptions {
Ok(data) => data,
Err(e) => {
let err_msg = format!("{e}");
write_error(err_msg);
error!(err_msg);
return Err(());
}
};
@ -392,13 +402,13 @@ async fn get_latest_prepub(volume_slug: &str) -> Result<Option<lemmy::PostInfoIn
Ok(data) => data,
Err(e) => {
let err_msg = format!("{e}");
write_error(err_msg);
error!(err_msg);
return Err(());
}
},
Err(e) => {
let err_msg = format!("{e}");
write_error(err_msg);
error!(err_msg);
return Err(());
}
};
@ -407,7 +417,7 @@ async fn get_latest_prepub(volume_slug: &str) -> Result<Option<lemmy::PostInfoIn
Ok(data) => data,
Err(e) => {
let err_msg = format!("{e}");
write_error(err_msg);
error!(err_msg);
return Err(());
}
};

View file

@ -1,5 +1,5 @@
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::lemmy_db_views::structs::PostView;
use lemmy_api_common::person::{Login, LoginResponse};
@ -10,6 +10,16 @@ use lemmy_db_schema::{ListingType, PostFeatureType};
use reqwest::StatusCode;
use std::collections::HashMap;
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 {
jwt_token: Sensitive<String>,
@ -45,7 +55,7 @@ pub(crate) async fn login(config: &Config) -> Result<Lemmy, ()> {
Ok(data) => data,
Err(e) => {
let err_msg = format!("{e}");
write_error(err_msg);
error!(err_msg);
return Err(());
}
};
@ -63,14 +73,14 @@ pub(crate) async fn login(config: &Config) -> Result<Lemmy, ()> {
}),
None => {
let err_msg = "Login did not return JWT token. Are the credentials valid?".to_owned();
write_error(err_msg);
error!(err_msg);
Err(())
}
}
}
status => {
let err_msg = format!("Unexpected HTTP Status '{}' during Login", status);
write_error(err_msg);
error!(err_msg);
Err(())
}
}
@ -273,14 +283,14 @@ impl Lemmy {
Ok(data) => data,
Err(e) => {
let err_msg = format!("{e}");
write_error(err_msg);
return Err(());
error!(err_msg);
Err(())
}
},
Err(e) => {
let err_msg = format!("{e}");
write_error(err_msg);
return Err(());
error!(err_msg);
Err(())
}
};
@ -288,8 +298,8 @@ impl Lemmy {
Ok(data) => data,
Err(e) => {
let err_msg = format!("{e}");
write_error(err_msg);
return Err(());
error!(err_msg);
Err(())
}
};

View file

@ -1,6 +1,24 @@
use crate::write_error;
use serde_derive::{Deserialize, Serialize};
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)]
pub(crate) struct SeriesHistory {
@ -9,6 +27,8 @@ pub(crate) struct SeriesHistory {
impl SeriesHistory {
pub(crate) fn load_history() -> Self {
let info_msg = "Loading History";
info!(info_msg);
match confy::load(env!("CARGO_PKG_NAME"), "history") {
Ok(data) => data,
Err(e) => panic!("history.toml not found: {e}"),
@ -16,9 +36,11 @@ impl SeriesHistory {
}
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) {
let err_msg = format!("Unexpected error saving to history.toml: {e}");
write_error(err_msg);
error!(err_msg);
}
}