Update logging macros usage in timer module

Replace log macros with custom logging macros in timer module
This commit is contained in:
Tunglies 2025-04-05 11:34:51 +08:00
parent 0de304d4e3
commit 0b8d08d13b
6 changed files with 76 additions and 78 deletions

View File

@ -103,7 +103,7 @@ pub async fn patch_profiles_config(profiles: IProfiles) -> CmdResult<bool> {
);
handle::Handle::notice_message(
"config_validate::file_not_found",
&format!("{}", file_path.display()),
format!("{}", file_path.display()),
);
return Ok(false);
}

View File

@ -1,4 +1,6 @@
use crate::{config::Config, core::CoreManager, feat, logging, utils::logging::Type};
use crate::{
config::Config, core::CoreManager, feat, logging, logging_error, utils::logging::Type,
};
use anyhow::{Context, Result};
use delay_timer::prelude::{DelayTimer, DelayTimerBuilder, TaskBuilder};
use once_cell::sync::OnceCell;
@ -54,7 +56,7 @@ impl Timer {
)
.is_err()
{
log::debug!(target: "app", "Timer already initialized, skipping...");
logging!(debug, Type::Timer, "Timer already initialized, skipping...");
return Ok(());
}
@ -65,7 +67,7 @@ impl Timer {
// Reset initialization flag on error
self.initialized
.store(false, std::sync::atomic::Ordering::SeqCst);
log::error!(target: "app", "Failed to initialize timer: {}", e);
logging_error!(Type::Timer, false, "Failed to initialize timer: {}", e);
return Err(e);
}
@ -98,15 +100,15 @@ impl Timer {
for uid in profiles_to_update {
if let Some(task) = timer_map.get(&uid) {
log::info!(target: "app", "Advancing task for uid: {}", uid);
logging!(info, Type::Timer, "Advancing task for uid: {}", uid);
if let Err(e) = delay_timer.advance_task(task.task_id) {
log::warn!(target: "app", "Failed to advance task {}: {}", uid, e);
logging!(warn, Type::Timer, "Failed to advance task {}: {}", uid, e);
}
}
}
}
log::info!(target: "app", "Timer initialization completed");
logging!(info, Type::Timer, "Timer initialization completed");
Ok(())
}
@ -116,11 +118,16 @@ impl Timer {
let diff_map = self.gen_diff();
if diff_map.is_empty() {
log::debug!(target: "app", "No timer changes needed");
logging!(debug, Type::Timer, "No timer changes needed");
return Ok(());
}
log::info!(target: "app", "Refreshing {} timer tasks", diff_map.len());
logging!(
info,
Type::Timer,
"Refreshing {} timer tasks",
diff_map.len()
);
// Apply changes while holding locks
let mut timer_map = self.timer_map.write();
@ -131,9 +138,16 @@ impl Timer {
DiffFlag::Del(tid) => {
timer_map.remove(&uid);
if let Err(e) = delay_timer.remove_task(tid) {
log::warn!(target: "app", "Failed to remove task {} for uid {}: {}", tid, uid, e);
logging!(
warn,
Type::Timer,
"Failed to remove task {} for uid {}: {}",
tid,
uid,
e
);
} else {
log::debug!(target: "app", "Removed task {} for uid {}", tid, uid);
logging!(debug, Type::Timer, "Removed task {} for uid {}", tid, uid);
}
}
DiffFlag::Add(tid, interval) => {
@ -146,16 +160,23 @@ impl Timer {
timer_map.insert(uid.clone(), task);
if let Err(e) = self.add_task(&mut delay_timer, uid.clone(), tid, interval) {
log::error!(target: "app", "Failed to add task for uid {}: {}", uid, e);
logging_error!(Type::Timer, "Failed to add task for uid {}: {}", uid, e);
timer_map.remove(&uid); // Rollback on failure
} else {
log::debug!(target: "app", "Added task {} for uid {}", tid, uid);
logging!(debug, Type::Timer, "Added task {} for uid {}", tid, uid);
}
}
DiffFlag::Mod(tid, interval) => {
// Remove old task first
if let Err(e) = delay_timer.remove_task(tid) {
log::warn!(target: "app", "Failed to remove old task {} for uid {}: {}", tid, uid, e);
logging!(
warn,
Type::Timer,
"Failed to remove old task {} for uid {}: {}",
tid,
uid,
e
);
}
// Then add the new one
@ -168,10 +189,10 @@ impl Timer {
timer_map.insert(uid.clone(), task);
if let Err(e) = self.add_task(&mut delay_timer, uid.clone(), tid, interval) {
log::error!(target: "app", "Failed to update task for uid {}: {}", uid, e);
logging_error!(Type::Timer, "Failed to update task for uid {}: {}", uid, e);
timer_map.remove(&uid); // Rollback on failure
} else {
log::debug!(target: "app", "Updated task {} for uid {}", tid, uid);
logging!(debug, Type::Timer, "Updated task {} for uid {}", tid, uid);
}
}
}
@ -250,7 +271,14 @@ impl Timer {
tid: TaskID,
minutes: u64,
) -> Result<()> {
log::info!(target: "app", "Adding task: uid={}, id={}, interval={}min", uid, tid, minutes);
logging!(
info,
Type::Timer,
"Adding task: uid={}, id={}, interval={}min",
uid,
tid,
minutes
);
// Create a task with reasonable retries and backoff
let task = TaskBuilder::default()
@ -275,7 +303,7 @@ impl Timer {
/// Async task with better error handling and logging
async fn async_task(uid: String) {
let task_start = std::time::Instant::now();
log::info!(target: "app", "Running timer task for profile: {}", uid);
logging!(info, Type::Timer, "Running timer task for profile: {}", uid);
// Update profile
let profile_result = feat::update_profile(uid.clone(), None).await;
@ -286,23 +314,26 @@ impl Timer {
match CoreManager::global().update_config().await {
Ok(_) => {
let duration = task_start.elapsed().as_millis();
log::info!(
target: "app",
logging!(
info,
Type::Timer,
"Timer task completed successfully for uid: {} (took {}ms)",
uid, duration
uid,
duration
);
}
Err(e) => {
log::error!(
target: "app",
logging_error!(
Type::Timer,
"Failed to refresh config after profile update for uid {}: {}",
uid, e
uid,
e
);
}
}
}
Err(e) => {
log::error!(target: "app", "Failed to update profile uid {}: {}", uid, e);
logging_error!(Type::Timer, "Failed to update profile uid {}: {}", uid, e);
}
}
}

View File

@ -6,8 +6,6 @@ use crate::{
module::mihomo::MihomoManager,
utils::resolve,
};
use tauri::Manager;
use tauri_plugin_window_state::{AppHandleExt, StateFlags};
/// Open or close the dashboard window
#[allow(dead_code)]
@ -51,39 +49,6 @@ pub fn open_or_close_dashboard() {
}
}
/// Setup window state monitor to save window position and size in real-time
pub fn setup_window_state_monitor(app_handle: &tauri::AppHandle) {
// 暂时移除实时监控-保存窗口位置和大小,这个特性可能会导致窗口异常大小和位置,需要进一步优化
//
// let window = app_handle.get_webview_window("main").unwrap();
// let app_handle_clone = app_handle.clone();
// // 监听窗口移动事件
// let app_handle_move = app_handle_clone.clone();
// window.on_window_event(move |event| {
// match event {
// // 窗口移动时保存状态
// tauri::WindowEvent::Moved(_) => {
// let _ = app_handle_move.save_window_state(StateFlags::all());
// }
// // 窗口调整大小时保存状态
// tauri::WindowEvent::Resized(_) => {
// let _ = app_handle_move.save_window_state(StateFlags::all());
// }
// // 其他可能改变窗口状态的事件
// tauri::WindowEvent::ScaleFactorChanged { .. } => {
// let _ = app_handle_move.save_window_state(StateFlags::all());
// }
// // 窗口关闭时保存
// tauri::WindowEvent::CloseRequested { .. } => {
// let _ = app_handle_move.save_window_state(StateFlags::all());
// }
// _ => {}
// }
// });
}
/// 优化的应用退出函数
pub fn quit(code: Option<i32>) {
log::debug!(target: "app", "启动退出流程");

View File

@ -13,7 +13,7 @@ use crate::{
const LIGHT_WEIGHT_TASK_UID: &str = "light_weight_task";
pub fn enable_auto_light_weight_mode() {
let _ = Timer::global().init().unwrap();
Timer::global().init().unwrap();
logging!(info, Type::Lightweight, true, "开启自动轻量模式");
setup_window_close_listener();
setup_webview_focus_listener();

View File

@ -39,10 +39,7 @@ impl PlatformSpecification {
// 使用默认值避免在同步上下文中执行异步操作
let running_mode = "NotRunning".to_string();
let is_admin = match system::is_admin() {
Ok(value) => value,
Err(_) => false,
};
let is_admin = system::is_admin().unwrap_or_default();
Self {
system_name,

View File

@ -86,12 +86,17 @@ macro_rules! wrap_err {
#[macro_export]
macro_rules! logging {
// 带 println 的版本(支持格式化参数)
($level:ident, $type:expr, $print:expr, $($arg:tt)*) => {
($level:ident, $type:expr, true, $($arg:tt)*) => {
println!("{} {}", $type, format_args!($($arg)*));
log::$level!(target: "app", "{} {}", $type, format_args!($($arg)*));
};
// 不带 println 的版本
// 带 println 的版本(使用 false 明确不打印)
($level:ident, $type:expr, false, $($arg:tt)*) => {
log::$level!(target: "app", "{} {}", $type, format_args!($($arg)*));
};
// 不带 print 参数的版本(默认不打印)
($level:ident, $type:expr, $($arg:tt)*) => {
log::$level!(target: "app", "{} {}", $type, format_args!($($arg)*));
};
@ -99,7 +104,7 @@ macro_rules! logging {
#[macro_export]
macro_rules! logging_error {
// Version with println and Result expression
// 1. 处理 Result<T, E>,带打印控制
($type:expr, $print:expr, $expr:expr) => {
match $expr {
Ok(_) => {},
@ -107,28 +112,28 @@ macro_rules! logging_error {
if $print {
println!("[{}] Error: {}", $type, err);
}
log::error!(target: "app", "{} {}", $type, err);
log::error!(target: "app", "[{}] {}", $type, err);
}
}
};
// Version without println and Result expression
// 2. 处理 Result<T, E>,默认不打印
($type:expr, $expr:expr) => {
if let Err(err) = $expr {
log::error!(target: "app", "{} {}", $type, err);
log::error!(target: "app", "[{}] {}", $type, err);
}
};
// Version with println and custom message
($type:expr, $print:expr, $($arg:tt)*) => {
// 3. 处理格式化字符串,带打印控制
($type:expr, $print:expr, $fmt:literal $(, $arg:expr)*) => {
if $print {
println!("[{}] {}", $type, format_args!($($arg)*));
println!("[{}] {}", $type, format_args!($fmt $(, $arg)*));
}
log::error!(target: "app", "{} {}", $type, format_args!($($arg)*));
log::error!(target: "app", "[{}] {}", $type, format_args!($fmt $(, $arg)*));
};
// Version without println and custom message
($type:expr, $($arg:tt)*) => {
log::error!(target: "app", "{} {}", $type, format_args!($($arg)*));
// 4. 处理格式化字符串,不带 bool 时,默认 `false`
($type:expr, $fmt:literal $(, $arg:expr)*) => {
logging_error!($type, false, $fmt $(, $arg)*);
};
}