Skip to content

Commit

Permalink
ref: 优化日志输出
Browse files Browse the repository at this point in the history
  • Loading branch information
SerenitySir committed Jul 24, 2024
1 parent 01bed51 commit 7215fc9
Show file tree
Hide file tree
Showing 3 changed files with 82 additions and 35 deletions.
25 changes: 21 additions & 4 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,21 @@ async fn main() {
util::logs::init("nal.log", level_filter).expect("初始化日志出错");

let cli = util::cmd::Cli::parse();
let service = Service::new("net-auto-login");
let service_res = Service::new("net-auto-login");
let service = match service_res {
Ok(ser) => { ser }
Err(err) => {
println!("创建服务出错!");
if !cfg!(debug_assertions) {
error!("创建服务出错:{}",err.to_string());
}
return;
}
};

// service.install();
// return;

if cli.install {
service.install();
service.start();
Expand All @@ -43,12 +57,15 @@ async fn main() {
handler(config).await;
return;
}
if cfg!(debug_assertions) {
handler(config).await
}
//默认直接运行
handler(config).await
}

async fn handler(config: NalConfig) {
println!("开始检测。。。");
if !cfg!(debug_assertions) {
info!("开始检测。。。");
}
loop {
//检测网络是否正常
let is_ok = nal::check_net().await;
Expand Down
35 changes: 21 additions & 14 deletions src/util/logs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ pub fn init(log_file: &str, level: LevelFilter) -> Result<(), Error> {
};
let logs_dir = current_dir + "/logs/";
fs::create_dir_all(logs_dir.clone()).unwrap(); // 如果需要,创建日志目录
// let log_file_path = logs_dir.clone().to_string() + log_file;
// let log_file_path = logs_dir.clone().to_string() + log_file;

init_tracing(logs_dir, log_file.to_string(), level);
Ok(())
Expand Down Expand Up @@ -153,7 +153,8 @@ fn init_tracing(logs_dir: String, log_file: String, level: LevelFilter) {
// time::format_description::well_known::Rfc3339;

let tracing_level = Level::from_str(level.as_str()).unwrap();
tracing_subscriber::fmt()

let builder = tracing_subscriber::fmt()
.with_file(true)
.with_level(true)
.with_target(true)
Expand All @@ -166,19 +167,25 @@ fn init_tracing(logs_dir: String, log_file: String, level: LevelFilter) {
time::macros::offset!(+8),
format,
))
.with_ansi(false)
.with_writer(
Mutex::new(tracing_appender::rolling::daily(
logs_dir.clone(),
log_file.clone(),
))
.and(
.with_ansi(false);
if cfg!(debug_assertions) {
builder
//调试模式输出到控制台
.with_writer(
//将 ERROR 及以上级别的日志输出到 stderr, 其他级别日志则输出到 stdout
std::io::stdout
.with_filter(|meta| meta.level() > &Level::ERROR)
.or_else(std::io::stderr),
),
)
.finish()
.init();
.or_else(std::io::stderr), )
.finish()
.init();
} else {
builder
//非调试模式输出到日志文件
.with_writer(Mutex::new(tracing_appender::rolling::daily(
logs_dir.clone(),
log_file.clone(),
)))
.finish()
.init();
}
}
57 changes: 40 additions & 17 deletions src/util/service.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
use std::env;
use std::ffi::OsString;
use std::path::PathBuf;
use log::{error, info};
use service_manager::{ScServiceManager, ServiceInstallCtx, ServiceLabel, ServiceManager, ServiceStartCtx, ServiceStopCtx, ServiceUninstallCtx};
use service_manager::{ScConfig, ScInstallConfig, ScServiceManager, ServiceInstallCtx, ServiceLabel, ServiceManager, ServiceStartCtx, ServiceStopCtx, ServiceUninstallCtx, WindowsErrorSeverity};

/// 系统服务
pub struct Service {
Expand All @@ -25,13 +24,13 @@ impl Service {
/// ```
/// let service = Service::new("nal");
/// ```
pub fn new(name: &str) -> Self {
Self {
name: name.parse().unwrap(),
path: env::current_exe().unwrap(),
pub fn new(name: &str) -> anyhow::Result<Self> {
Ok(Self {
name: name.parse()?,
path: env::current_exe()?,
// 通过检测平台上可用的内容来获得通用服务
service_manage: Box::from(ScServiceManager::system()),
}
service_manage: <dyn ServiceManager>::native()?,
})
}

/// 安装到系统服务
Expand All @@ -40,7 +39,7 @@ impl Service {
let result = self.service_manage.install(ServiceInstallCtx {
label: self.name.clone(),
program: self.path.clone(),
args: vec![OsString::from("--run")],
args: vec![],
contents: None, // 特定于系统的服务内容的可选字符串。
username: None, // 可选字符串,供备用用户运行服务。
working_directory: Option::from(self.path.parent().unwrap().to_path_buf()), // 服务进程的工作目录的可选字符串。
Expand All @@ -49,10 +48,16 @@ impl Service {
});
match result {
Ok(_) => {
info!("{}服务安装完成。",self.name.clone().to_string())
if !cfg!(debug_assertions) {
info!("{}服务安装完成。",self.name.clone().to_string());
}
println!("{}服务安装完成。", self.name.clone().to_string())
}
Err(err) => {
error!("{}服务安装失败:{}",self.name.clone().to_string(),err.to_string())
if !cfg!(debug_assertions) {
error!("{}服务安装失败:{}",self.name.clone().to_string(),err.to_string())
}
println!("{}服务安装失败:{}", self.name.clone().to_string(), err.to_string())
}
}
}
Expand All @@ -65,10 +70,16 @@ impl Service {
});
match result {
Ok(_) => {
info!("{}服务卸载完成。",self.name.clone().to_string())
if !cfg!(debug_assertions) {
info!("{}服务卸载完成。",self.name.clone().to_string());
}
println!("{}服务卸载完成。", self.name.clone().to_string())
}
Err(err) => {
error!("{}服务卸载失败:{}",self.name.clone().to_string(),err.to_string())
if !cfg!(debug_assertions) {
error!("{}服务卸载失败:{}",self.name.clone().to_string(),err.to_string());
}
println!("{}服务卸载失败:{}", self.name.clone().to_string(), err.to_string())
}
}
}
Expand All @@ -81,10 +92,16 @@ impl Service {
});
match result {
Ok(_) => {
info!("{}服务启动完成。",self.name.clone().to_string())
if !cfg!(debug_assertions) {
info!("{}服务启动完成。",self.name.clone().to_string());
}
println!("{}服务启动完成。", self.name.clone().to_string())
}
Err(err) => {
error!("{}服务启动失败:{}",self.name.clone().to_string(), err.to_string())
if !cfg!(debug_assertions) {
error!("{}服务启动失败:{}",self.name.clone().to_string(), err.to_string());
}
println!("{}服务启动失败:{}", self.name.clone().to_string(), err.to_string())
}
}
}
Expand All @@ -97,10 +114,16 @@ impl Service {
});
match result {
Ok(_) => {
info!("{}服务停止完成。",self.name.clone().to_string());
if !cfg!(debug_assertions) {
info!("{}服务停止完成。",self.name.clone().to_string());
}
println!("{}服务停止完成。", self.name.clone().to_string());
}
Err(err) => {
info!("{}服务停止失败:{}",self.name.clone().to_string(),err.to_string());
if !cfg!(debug_assertions) {
info!("{}服务停止失败:{}",self.name.clone().to_string(),err.to_string());
}
println!("{}服务停止失败:{}", self.name.clone().to_string(), err.to_string());
}
}
}
Expand Down

0 comments on commit 7215fc9

Please sign in to comment.