mirror of
https://github.com/clash-verge-rev/clash-verge-rev
synced 2025-05-05 12:53:44 +08:00
refactor: logger fetch logic
This commit is contained in:
parent
132641f269
commit
221b732472
@ -8,7 +8,7 @@ use crate::{ret_err, wrap_err};
|
|||||||
use anyhow::{Context, Result};
|
use anyhow::{Context, Result};
|
||||||
use network_interface::NetworkInterface;
|
use network_interface::NetworkInterface;
|
||||||
use serde_yaml::Mapping;
|
use serde_yaml::Mapping;
|
||||||
use std::collections::{HashMap, VecDeque};
|
use std::collections::HashMap;
|
||||||
use sysproxy::{Autoproxy, Sysproxy};
|
use sysproxy::{Autoproxy, Sysproxy};
|
||||||
type CmdResult<T = ()> = Result<T, String>;
|
type CmdResult<T = ()> = Result<T, String>;
|
||||||
use reqwest_dav::list_cmd::ListFile;
|
use reqwest_dav::list_cmd::ListFile;
|
||||||
@ -216,11 +216,6 @@ pub fn get_auto_proxy() -> CmdResult<Mapping> {
|
|||||||
Ok(map)
|
Ok(map)
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tauri::command]
|
|
||||||
pub fn get_clash_logs() -> CmdResult<VecDeque<String>> {
|
|
||||||
Ok(logger::Logger::global().get_log())
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
pub fn open_app_dir() -> CmdResult<()> {
|
pub fn open_app_dir() -> CmdResult<()> {
|
||||||
let app_dir = wrap_err!(dirs::app_home_dir())?;
|
let app_dir = wrap_err!(dirs::app_home_dir())?;
|
||||||
|
@ -96,8 +96,7 @@ pub fn parse_log(log: String) -> String {
|
|||||||
log
|
log
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 缩短clash -t的错误输出
|
#[allow(dead_code)]
|
||||||
/// 仅适配 clash p核 8-26、clash meta 1.13.1
|
|
||||||
pub fn parse_check_output(log: String) -> String {
|
pub fn parse_check_output(log: String) -> String {
|
||||||
let t = log.find("time=");
|
let t = log.find("time=");
|
||||||
let m = log.find("msg=");
|
let m = log.find("msg=");
|
||||||
|
@ -1,5 +1,5 @@
|
|||||||
use crate::config::*;
|
use crate::config::*;
|
||||||
use crate::core::{clash_api, handle, logger::Logger, service};
|
use crate::core::{clash_api, handle, service};
|
||||||
use crate::log_err;
|
use crate::log_err;
|
||||||
use crate::utils::dirs;
|
use crate::utils::dirs;
|
||||||
use anyhow::{bail, Result};
|
use anyhow::{bail, Result};
|
||||||
@ -43,24 +43,13 @@ impl CoreManager {
|
|||||||
let test_dir = dirs::path_to_str(&test_dir)?;
|
let test_dir = dirs::path_to_str(&test_dir)?;
|
||||||
let app_handle = handle::Handle::global().app_handle().unwrap();
|
let app_handle = handle::Handle::global().app_handle().unwrap();
|
||||||
|
|
||||||
let output = app_handle
|
let _ = app_handle
|
||||||
.shell()
|
.shell()
|
||||||
.sidecar(clash_core)?
|
.sidecar(clash_core)?
|
||||||
.args(["-t", "-d", test_dir, "-f", config_path])
|
.args(["-t", "-d", test_dir, "-f", config_path])
|
||||||
.output()
|
.output()
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
if !output.status.success() {
|
|
||||||
let stdout = String::from_utf8(output.stdout).unwrap_or_default();
|
|
||||||
let error = clash_api::parse_check_output(stdout.clone());
|
|
||||||
let error = match !error.is_empty() {
|
|
||||||
true => error,
|
|
||||||
false => stdout.clone(),
|
|
||||||
};
|
|
||||||
Logger::global().set_log(stdout.clone());
|
|
||||||
bail!("{error}");
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -136,9 +125,6 @@ impl CoreManager {
|
|||||||
|
|
||||||
self.check_config().await?;
|
self.check_config().await?;
|
||||||
|
|
||||||
// 清掉旧日志
|
|
||||||
Logger::global().clear_log();
|
|
||||||
|
|
||||||
match self.restart_core().await {
|
match self.restart_core().await {
|
||||||
Ok(_) => {
|
Ok(_) => {
|
||||||
Config::verge().apply();
|
Config::verge().apply();
|
||||||
|
@ -1,36 +0,0 @@
|
|||||||
use once_cell::sync::OnceCell;
|
|
||||||
use parking_lot::Mutex;
|
|
||||||
use std::{collections::VecDeque, sync::Arc};
|
|
||||||
|
|
||||||
const LOGS_QUEUE_LEN: usize = 100;
|
|
||||||
|
|
||||||
pub struct Logger {
|
|
||||||
log_data: Arc<Mutex<VecDeque<String>>>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Logger {
|
|
||||||
pub fn global() -> &'static Logger {
|
|
||||||
static LOGGER: OnceCell<Logger> = OnceCell::new();
|
|
||||||
|
|
||||||
LOGGER.get_or_init(|| Logger {
|
|
||||||
log_data: Arc::new(Mutex::new(VecDeque::with_capacity(LOGS_QUEUE_LEN + 10))),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn get_log(&self) -> VecDeque<String> {
|
|
||||||
self.log_data.lock().clone()
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn set_log(&self, text: String) {
|
|
||||||
let mut logs = self.log_data.lock();
|
|
||||||
if logs.len() > LOGS_QUEUE_LEN {
|
|
||||||
logs.pop_front();
|
|
||||||
}
|
|
||||||
logs.push_back(text);
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn clear_log(&self) {
|
|
||||||
let mut logs = self.log_data.lock();
|
|
||||||
logs.clear();
|
|
||||||
}
|
|
||||||
}
|
|
@ -4,7 +4,6 @@ pub mod clash_api;
|
|||||||
mod core;
|
mod core;
|
||||||
pub mod handle;
|
pub mod handle;
|
||||||
pub mod hotkey;
|
pub mod hotkey;
|
||||||
pub mod logger;
|
|
||||||
pub mod service;
|
pub mod service;
|
||||||
pub mod sysopt;
|
pub mod sysopt;
|
||||||
pub mod timer;
|
pub mod timer;
|
||||||
|
@ -88,7 +88,6 @@ pub fn run() {
|
|||||||
cmds::restart_app,
|
cmds::restart_app,
|
||||||
// clash
|
// clash
|
||||||
cmds::get_clash_info,
|
cmds::get_clash_info,
|
||||||
cmds::get_clash_logs,
|
|
||||||
cmds::patch_clash_config,
|
cmds::patch_clash_config,
|
||||||
cmds::change_clash_core,
|
cmds::change_clash_core,
|
||||||
cmds::get_runtime_config,
|
cmds::get_runtime_config,
|
||||||
|
@ -3,29 +3,35 @@ import { useEnableLog } from "../services/states";
|
|||||||
import { createSockette } from "../utils/websocket";
|
import { createSockette } from "../utils/websocket";
|
||||||
import { useClashInfo } from "./use-clash";
|
import { useClashInfo } from "./use-clash";
|
||||||
import dayjs from "dayjs";
|
import dayjs from "dayjs";
|
||||||
import { getClashLogs } from "../services/cmds";
|
|
||||||
|
|
||||||
const MAX_LOG_NUM = 1000;
|
const MAX_LOG_NUM = 1000;
|
||||||
|
|
||||||
export const useLogData = () => {
|
// 添加 LogLevel 类型定义
|
||||||
|
export type LogLevel = "warning" | "info" | "debug" | "error";
|
||||||
|
|
||||||
|
const buildWSUrl = (server: string, secret: string, logLevel: LogLevel) => {
|
||||||
|
const baseUrl = `ws://${server}/logs`;
|
||||||
|
const params = new URLSearchParams();
|
||||||
|
|
||||||
|
if (secret) {
|
||||||
|
params.append("token", encodeURIComponent(secret));
|
||||||
|
}
|
||||||
|
params.append("level", logLevel);
|
||||||
|
const queryString = params.toString();
|
||||||
|
return queryString ? `${baseUrl}?${queryString}` : baseUrl;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const useLogData = (logLevel: LogLevel) => {
|
||||||
const { clashInfo } = useClashInfo();
|
const { clashInfo } = useClashInfo();
|
||||||
|
|
||||||
const [enableLog] = useEnableLog();
|
const [enableLog] = useEnableLog();
|
||||||
|
|
||||||
return useSWRSubscription<ILogItem[], any, "getClashLog" | null>(
|
return useSWRSubscription<ILogItem[], any, [string, LogLevel] | null>(
|
||||||
enableLog && clashInfo ? "getClashLog" : null,
|
enableLog && clashInfo ? ["getClashLog", logLevel] : null,
|
||||||
(_key, { next }) => {
|
(_key, { next }) => {
|
||||||
const { server = "", secret = "" } = clashInfo!;
|
const { server = "", secret = "" } = clashInfo!;
|
||||||
|
|
||||||
// populate the initial logs
|
const s = createSockette(buildWSUrl(server, secret, logLevel), {
|
||||||
getClashLogs().then(
|
|
||||||
(logs) => next(null, logs),
|
|
||||||
(err) => next(err)
|
|
||||||
);
|
|
||||||
|
|
||||||
const s = createSockette(
|
|
||||||
`ws://${server}/logs?token=${encodeURIComponent(secret)}`,
|
|
||||||
{
|
|
||||||
onmessage(event) {
|
onmessage(event) {
|
||||||
const data = JSON.parse(event.data) as ILogItem;
|
const data = JSON.parse(event.data) as ILogItem;
|
||||||
|
|
||||||
@ -41,8 +47,7 @@ export const useLogData = () => {
|
|||||||
this.close();
|
this.close();
|
||||||
next(event);
|
next(event);
|
||||||
},
|
},
|
||||||
}
|
});
|
||||||
);
|
|
||||||
|
|
||||||
return () => {
|
return () => {
|
||||||
s.close();
|
s.close();
|
||||||
|
@ -6,7 +6,7 @@ import {
|
|||||||
PlayCircleOutlineRounded,
|
PlayCircleOutlineRounded,
|
||||||
PauseCircleOutlineRounded,
|
PauseCircleOutlineRounded,
|
||||||
} from "@mui/icons-material";
|
} from "@mui/icons-material";
|
||||||
import { useLogData } from "@/hooks/use-log-data";
|
import { useLogData, LogLevel } from "@/hooks/use-log-data";
|
||||||
import { useEnableLog } from "@/services/states";
|
import { useEnableLog } from "@/services/states";
|
||||||
import { BaseEmpty, BasePage } from "@/components/base";
|
import { BaseEmpty, BasePage } from "@/components/base";
|
||||||
import LogItem from "@/components/log/log-item";
|
import LogItem from "@/components/log/log-item";
|
||||||
@ -17,19 +17,19 @@ import { mutate } from "swr";
|
|||||||
|
|
||||||
const LogPage = () => {
|
const LogPage = () => {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
const { data: logData = [] } = useLogData();
|
|
||||||
const [enableLog, setEnableLog] = useEnableLog();
|
const [enableLog, setEnableLog] = useEnableLog();
|
||||||
const theme = useTheme();
|
const theme = useTheme();
|
||||||
const isDark = theme.palette.mode === "dark";
|
const isDark = theme.palette.mode === "dark";
|
||||||
const [logState, setLogState] = useState("all");
|
const [logState, setLogState] = useState<LogLevel>("info");
|
||||||
const [match, setMatch] = useState(() => (_: string) => true);
|
const [match, setMatch] = useState(() => (_: string) => true);
|
||||||
|
const { data: logData } = useLogData(logState);
|
||||||
|
|
||||||
const filterLogs = useMemo(() => {
|
const filterLogs = useMemo(() => {
|
||||||
return logData.filter(
|
return logData
|
||||||
(data) =>
|
? logData.filter(
|
||||||
(logState === "all" ? true : data.type.includes(logState)) &&
|
(data) => data.type.includes(logState) && match(data.payload)
|
||||||
match(data.payload)
|
)
|
||||||
);
|
: [];
|
||||||
}, [logData, logState, match]);
|
}, [logData, logState, match]);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
@ -80,12 +80,12 @@ const LogPage = () => {
|
|||||||
>
|
>
|
||||||
<BaseStyledSelect
|
<BaseStyledSelect
|
||||||
value={logState}
|
value={logState}
|
||||||
onChange={(e) => setLogState(e.target.value)}
|
onChange={(e) => setLogState(e.target.value as LogLevel)}
|
||||||
>
|
>
|
||||||
<MenuItem value="all">ALL</MenuItem>
|
<MenuItem value="info">INFO</MenuItem>
|
||||||
<MenuItem value="inf">INFO</MenuItem>
|
<MenuItem value="warning">WARN</MenuItem>
|
||||||
<MenuItem value="warn">WARN</MenuItem>
|
<MenuItem value="error">ERROR</MenuItem>
|
||||||
<MenuItem value="err">ERROR</MenuItem>
|
<MenuItem value="debug">DEBUG</MenuItem>
|
||||||
</BaseStyledSelect>
|
</BaseStyledSelect>
|
||||||
<BaseSearchBox onSearch={(match) => setMatch(() => match)} />
|
<BaseSearchBox onSearch={(match) => setMatch(() => match)} />
|
||||||
</Box>
|
</Box>
|
||||||
|
@ -6,29 +6,6 @@ export async function copyClashEnv() {
|
|||||||
return invoke<void>("copy_clash_env");
|
return invoke<void>("copy_clash_env");
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function getClashLogs() {
|
|
||||||
const regex = /time="(.+?)"\s+level=(.+?)\s+msg="(.+?)"/;
|
|
||||||
const newRegex = /(.+?)\s+(.+?)\s+(.+)/;
|
|
||||||
const logs = await invoke<string[]>("get_clash_logs");
|
|
||||||
|
|
||||||
return logs.reduce<ILogItem[]>((acc, log) => {
|
|
||||||
const result = log.match(regex);
|
|
||||||
if (result) {
|
|
||||||
const [_, _time, type, payload] = result;
|
|
||||||
const time = dayjs(_time).format("MM-DD HH:mm:ss");
|
|
||||||
acc.push({ time, type, payload });
|
|
||||||
return acc;
|
|
||||||
}
|
|
||||||
|
|
||||||
const result2 = log.match(newRegex);
|
|
||||||
if (result2) {
|
|
||||||
const [_, time, type, payload] = result2;
|
|
||||||
acc.push({ time, type, payload });
|
|
||||||
}
|
|
||||||
return acc;
|
|
||||||
}, []);
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function getProfiles() {
|
export async function getProfiles() {
|
||||||
return invoke<IProfilesConfig>("get_profiles");
|
return invoke<IProfilesConfig>("get_profiles");
|
||||||
}
|
}
|
||||||
|
Loading…
x
Reference in New Issue
Block a user