将日志保存到文件

This commit is contained in:
2026-01-29 20:37:23 +08:00
parent d8917639af
commit 09a42be3cf

View File

@@ -6,6 +6,8 @@ use chrono::Local;
use colored::{Color, Colorize}; use colored::{Color, Colorize};
use fern::Dispatch; use fern::Dispatch;
use log::Level; use log::Level;
use std::env;
use std::path::PathBuf;
#[tokio::main] #[tokio::main]
async fn main() { async fn main() {
@@ -23,6 +25,19 @@ fn get_time() -> String {
now.format("%Y-%m-%d %H:%M:%S").to_string() now.format("%Y-%m-%d %H:%M:%S").to_string()
} }
pub fn get_current_dir() -> PathBuf {
PathBuf::from(
env::current_exe()
.expect("获取可执行文件路径失败!")
.parent()
.expect("获取可执行文件所在目录失败!"),
)
}
pub fn get_log_path() -> PathBuf {
get_current_dir().join("logs")
}
fn init_log() { fn init_log() {
let mut console_dispatch = Dispatch::new() let mut console_dispatch = Dispatch::new()
.format(|out, message, record| { .format(|out, message, record| {
@@ -42,6 +57,7 @@ fn init_log() {
)) ))
}) })
.chain(std::io::stdout()) .chain(std::io::stdout())
.chain(fern::log_file(get_log_path().join("app.log")).expect("无法打开日志文件"))
.level(log::LevelFilter::Debug); .level(log::LevelFilter::Debug);
console_dispatch.apply().expect("写入日志失败"); console_dispatch.apply().expect("写入日志失败");
} }