refactor: logger fetch logic

This commit is contained in:
huzibaca
2024-11-18 05:58:06 +08:00
parent 824325a2eb
commit 9ebd96611a
9 changed files with 50 additions and 126 deletions

View File

@@ -3,46 +3,51 @@ import { useEnableLog } from "../services/states";
import { createSockette } from "../utils/websocket";
import { useClashInfo } from "./use-clash";
import dayjs from "dayjs";
import { getClashLogs } from "../services/cmds";
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 [enableLog] = useEnableLog();
return useSWRSubscription<ILogItem[], any, "getClashLog" | null>(
enableLog && clashInfo ? "getClashLog" : null,
return useSWRSubscription<ILogItem[], any, [string, LogLevel] | null>(
enableLog && clashInfo ? ["getClashLog", logLevel] : null,
(_key, { next }) => {
const { server = "", secret = "" } = clashInfo!;
// populate the initial logs
getClashLogs().then(
(logs) => next(null, logs),
(err) => next(err)
);
const s = createSockette(buildWSUrl(server, secret, logLevel), {
onmessage(event) {
const data = JSON.parse(event.data) as ILogItem;
const s = createSockette(
`ws://${server}/logs?token=${encodeURIComponent(secret)}`,
{
onmessage(event) {
const data = JSON.parse(event.data) as ILogItem;
// append new log item on socket message
next(null, (l = []) => {
const time = dayjs().format("MM-DD HH:mm:ss");
// append new log item on socket message
next(null, (l = []) => {
const time = dayjs().format("MM-DD HH:mm:ss");
if (l.length >= MAX_LOG_NUM) l.shift();
return [...l, { ...data, time }];
});
},
onerror(event) {
this.close();
next(event);
},
}
);
if (l.length >= MAX_LOG_NUM) l.shift();
return [...l, { ...data, time }];
});
},
onerror(event) {
this.close();
next(event);
},
});
return () => {
s.close();

View File

@@ -6,7 +6,7 @@ import {
PlayCircleOutlineRounded,
PauseCircleOutlineRounded,
} 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 { BaseEmpty, BasePage } from "@/components/base";
import LogItem from "@/components/log/log-item";
@@ -17,19 +17,19 @@ import { mutate } from "swr";
const LogPage = () => {
const { t } = useTranslation();
const { data: logData = [] } = useLogData();
const [enableLog, setEnableLog] = useEnableLog();
const theme = useTheme();
const isDark = theme.palette.mode === "dark";
const [logState, setLogState] = useState("all");
const [logState, setLogState] = useState<LogLevel>("info");
const [match, setMatch] = useState(() => (_: string) => true);
const { data: logData } = useLogData(logState);
const filterLogs = useMemo(() => {
return logData.filter(
(data) =>
(logState === "all" ? true : data.type.includes(logState)) &&
match(data.payload)
);
return logData
? logData.filter(
(data) => data.type.includes(logState) && match(data.payload)
)
: [];
}, [logData, logState, match]);
return (
@@ -80,12 +80,12 @@ const LogPage = () => {
>
<BaseStyledSelect
value={logState}
onChange={(e) => setLogState(e.target.value)}
onChange={(e) => setLogState(e.target.value as LogLevel)}
>
<MenuItem value="all">ALL</MenuItem>
<MenuItem value="inf">INFO</MenuItem>
<MenuItem value="warn">WARN</MenuItem>
<MenuItem value="err">ERROR</MenuItem>
<MenuItem value="info">INFO</MenuItem>
<MenuItem value="warning">WARN</MenuItem>
<MenuItem value="error">ERROR</MenuItem>
<MenuItem value="debug">DEBUG</MenuItem>
</BaseStyledSelect>
<BaseSearchBox onSearch={(match) => setMatch(() => match)} />
</Box>

View File

@@ -6,29 +6,6 @@ export async function copyClashEnv() {
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() {
return invoke<IProfilesConfig>("get_profiles");
}