feat: improve log rule

This commit is contained in:
GyDi 2022-07-17 17:39:44 +08:00
parent 659fdd1d37
commit 4f6fceb87f
No known key found for this signature in database
GPG Key ID: 58B15242BA8277A6
8 changed files with 33 additions and 33 deletions

View File

@ -418,7 +418,7 @@ impl Core {
let result = event.payload(); let result = event.payload();
if result.is_none() { if result.is_none() {
log::warn!("event payload result is none"); log::warn!(target: "app", "event payload result is none");
return; return;
} }
@ -438,10 +438,10 @@ impl Core {
let service = service.lock(); let service = service.lock();
log_if_err!(service.set_config(info, config, notice)); log_if_err!(service.set_config(info, config, notice));
log::info!("profile enhanced status {}", result.status); log::info!(target: "app", "profile enhanced status {}", result.status);
} }
result.error.map(|err| log::error!("{err}")); result.error.map(|err| log::error!(target: "app", "{err}"));
}); });
let verge = self.verge.lock(); let verge = self.verge.lock();

View File

@ -53,12 +53,10 @@ impl Service {
Ok(status) => { Ok(status) => {
// 未启动clash // 未启动clash
if status.code != 0 { if status.code != 0 {
if let Err(err) = Self::start_clash_by_service().await { log_if_err!(Self::start_clash_by_service().await);
log::error!("{err}");
} }
} }
} Err(err) => log::error!(target: "app", "{err}"),
Err(err) => log::error!("{err}"),
} }
}); });
@ -77,9 +75,7 @@ impl Service {
} }
tauri::async_runtime::spawn(async move { tauri::async_runtime::spawn(async move {
if let Err(err) = Self::stop_clash_by_service().await { log_if_err!(Self::stop_clash_by_service().await);
log::error!("{err}");
}
}); });
Ok(()) Ok(())
@ -109,8 +105,11 @@ impl Service {
tauri::async_runtime::spawn(async move { tauri::async_runtime::spawn(async move {
while let Some(event) = rx.recv().await { while let Some(event) = rx.recv().await {
match event { match event {
CommandEvent::Stdout(line) => log::info!("[clash]: {}", line), CommandEvent::Stdout(line) => {
CommandEvent::Stderr(err) => log::error!("[clash]: {}", err), let stdout = if line.len() > 33 { &line[33..] } else { &line };
log::info!(target: "app" ,"[clash]: {}", stdout);
}
CommandEvent::Stderr(err) => log::error!(target: "app" ,"[clash error]: {}", err),
_ => {} _ => {}
} }
} }
@ -152,7 +151,7 @@ impl Service {
match builder.send().await { match builder.send().await {
Ok(resp) => { Ok(resp) => {
if resp.status() != 204 { if resp.status() != 204 {
log::error!("failed to activate clash with status \"{}\"", resp.status()); log::error!(target: "app", "failed to activate clash with status \"{}\"", resp.status());
} }
notice.refresh_clash(); notice.refresh_clash();
@ -160,10 +159,10 @@ impl Service {
// do not retry // do not retry
break; break;
} }
Err(err) => log::error!("failed to activate for `{err}`"), Err(err) => log::error!(target: "app", "failed to activate for `{err}`"),
} }
} }
Err(err) => log::error!("failed to activate for `{err}`"), Err(err) => log::error!(target: "app", "failed to activate for `{err}`"),
} }
sleep(Duration::from_millis(500)).await; sleep(Duration::from_millis(500)).await;
} }
@ -186,7 +185,7 @@ impl Service {
match builder.send().await { match builder.send().await {
Ok(_) => notice.refresh_clash(), Ok(_) => notice.refresh_clash(),
Err(err) => log::error!("{err}"), Err(err) => log::error!(target: "app", "{err}"),
} }
} }
}); });

View File

@ -2,7 +2,6 @@ use super::{Clash, Verge};
use crate::{log_if_err, utils::sysopt::SysProxyConfig}; use crate::{log_if_err, utils::sysopt::SysProxyConfig};
use anyhow::{bail, Result}; use anyhow::{bail, Result};
use auto_launch::{AutoLaunch, AutoLaunchBuilder}; use auto_launch::{AutoLaunch, AutoLaunchBuilder};
// use parking_lot::Mutex;
use std::sync::Arc; use std::sync::Arc;
use tauri::{async_runtime::Mutex, utils::platform::current_exe}; use tauri::{async_runtime::Mutex, utils::platform::current_exe};
@ -46,7 +45,7 @@ impl Sysopt {
if enable { if enable {
if let Err(err) = sysproxy.set_sys() { if let Err(err) = sysproxy.set_sys() {
log::error!("failed to set system proxy for `{err}`"); log::error!(target: "app", "failed to set system proxy for `{err}`");
} }
} }
@ -90,7 +89,7 @@ impl Sysopt {
if let Some(sysproxy) = self.old_sysproxy.take() { if let Some(sysproxy) = self.old_sysproxy.take() {
match sysproxy.set_sys() { match sysproxy.set_sys() {
Ok(_) => self.cur_sysproxy = None, Ok(_) => self.cur_sysproxy = None,
Err(_) => log::error!("failed to reset proxy"), Err(_) => log::error!(target: "app", "failed to reset proxy"),
} }
} }
} }
@ -183,7 +182,7 @@ impl Sysopt {
break; break;
} }
log::debug!("try to guard the system proxy"); log::debug!(target: "app", "try to guard the system proxy");
let clash = Clash::new(); let clash = Clash::new();
@ -194,7 +193,7 @@ impl Sysopt {
log_if_err!(sysproxy.set_sys()); log_if_err!(sysproxy.set_sys());
} }
None => log::error!("failed to parse clash port"), None => log::error!(target: "app", "failed to parse clash port"),
} }
} }

View File

@ -139,7 +139,7 @@ impl Timer {
/// the task runner /// the task runner
async fn async_task(core: Core, uid: String) { async fn async_task(core: Core, uid: String) {
log::info!("running timer task `{uid}`"); log::info!(target: "app", "running timer task `{uid}`");
log_if_err!(Core::update_profile_item(core, uid, None).await); log_if_err!(Core::update_profile_item(core, uid, None).await);
} }
} }

View File

@ -5,7 +5,7 @@ use std::{fs, path::PathBuf};
/// read data from yaml as struct T /// read data from yaml as struct T
pub fn read_yaml<T: DeserializeOwned + Default>(path: PathBuf) -> T { pub fn read_yaml<T: DeserializeOwned + Default>(path: PathBuf) -> T {
if !path.exists() { if !path.exists() {
log::error!("file not found \"{}\"", path.display()); log::error!(target: "app", "file not found \"{}\"", path.display());
return T::default(); return T::default();
} }
@ -14,7 +14,7 @@ pub fn read_yaml<T: DeserializeOwned + Default>(path: PathBuf) -> T {
match serde_yaml::from_str::<T>(&yaml_str) { match serde_yaml::from_str::<T>(&yaml_str) {
Ok(val) => val, Ok(val) => val,
Err(_) => { Err(_) => {
log::error!("failed to read yaml file \"{}\"", path.display()); log::error!(target: "app", "failed to read yaml file \"{}\"", path.display());
T::default() T::default()
} }
} }

View File

@ -80,7 +80,7 @@ pub fn open_file(path: PathBuf) -> Result<()> {
macro_rules! log_if_err { macro_rules! log_if_err {
($result: expr) => { ($result: expr) => {
if let Err(err) = $result { if let Err(err) = $result {
log::error!("{err}"); log::error!(target: "app", "{err}");
} }
}; };
} }
@ -93,7 +93,7 @@ macro_rules! wrap_err {
match $stat { match $stat {
Ok(a) => Ok(a), Ok(a) => Ok(a),
Err(err) => { Err(err) => {
log::error!("{}", err.to_string()); log::error!(target: "app", "{}", err.to_string());
Err(format!("{}", err.to_string())) Err(format!("{}", err.to_string()))
} }
} }

View File

@ -3,7 +3,7 @@ use chrono::Local;
use log::LevelFilter; use log::LevelFilter;
use log4rs::append::console::ConsoleAppender; use log4rs::append::console::ConsoleAppender;
use log4rs::append::file::FileAppender; use log4rs::append::file::FileAppender;
use log4rs::config::{Appender, Config, Root}; use log4rs::config::{Appender, Config, Logger, Root};
use log4rs::encode::pattern::PatternEncoder; use log4rs::encode::pattern::PatternEncoder;
use std::fs; use std::fs;
use std::io::Write; use std::io::Write;
@ -28,11 +28,13 @@ fn init_log(log_dir: &PathBuf) {
let config = Config::builder() let config = Config::builder()
.appender(Appender::builder().build("stdout", Box::new(stdout))) .appender(Appender::builder().build("stdout", Box::new(stdout)))
.appender(Appender::builder().build("file", Box::new(tofile))) .appender(Appender::builder().build("file", Box::new(tofile)))
.build( .logger(
Root::builder() Logger::builder()
.appenders(["stdout", "file"]) .appenders(["file", "stdout"])
.build(LevelFilter::Info), .additive(false)
.build("app", LevelFilter::Info),
) )
.build(Root::builder().appender("stdout").build(LevelFilter::Info))
.unwrap(); .unwrap();
log4rs::init_config(config).unwrap(); log4rs::init_config(config).unwrap();
@ -78,7 +80,7 @@ pub fn init_app(package_info: &PackageInfo) {
init_log(&log_dir); init_log(&log_dir);
if let Err(err) = init_config(&app_dir) { if let Err(err) = init_config(&app_dir) {
log::error!("{err}"); log::error!(target: "app", "{err}");
} }
// copy the resource file // copy the resource file

View File

@ -111,7 +111,7 @@ pub fn create_window(app_handle: &AppHandle) {
} }
}); });
} }
Err(err) => log::error!("{err}"), Err(err) => log::error!(target: "app", "{err}"),
} }
} }