feat: refactor logging system into a global service
This commit is contained in:
@@ -5,18 +5,19 @@ import { useClashInfo } from "./use-clash";
|
||||
import dayjs from "dayjs";
|
||||
import { create } from "zustand";
|
||||
import { useVisibility } from "./use-visibility";
|
||||
import {
|
||||
useGlobalLogData,
|
||||
clearGlobalLogs,
|
||||
LogLevel,
|
||||
ILogItem,
|
||||
} from "@/services/global-log-service";
|
||||
|
||||
// 为了向后兼容,导出相同的类型
|
||||
export type { LogLevel };
|
||||
export type { ILogItem };
|
||||
|
||||
const MAX_LOG_NUM = 1000;
|
||||
|
||||
export type LogLevel = "warning" | "info" | "debug" | "error" | "all";
|
||||
|
||||
interface ILogItem {
|
||||
time?: string;
|
||||
type: string;
|
||||
payload: string;
|
||||
[key: string]: any;
|
||||
}
|
||||
|
||||
const buildWSUrl = (server: string, secret: string, logLevel: LogLevel) => {
|
||||
const baseUrl = `ws://${server}/logs`;
|
||||
const params = new URLSearchParams();
|
||||
@@ -57,45 +58,6 @@ const useLogStore = create<LogStore>(
|
||||
}),
|
||||
);
|
||||
|
||||
export const useLogData = (logLevel: LogLevel) => {
|
||||
const { clashInfo } = useClashInfo();
|
||||
const [enableLog] = useEnableLog();
|
||||
const { logs, appendLog } = useLogStore();
|
||||
const pageVisible = useVisibility();
|
||||
export const useLogData = useGlobalLogData;
|
||||
|
||||
useEffect(() => {
|
||||
if (!enableLog || !clashInfo || !pageVisible) return;
|
||||
|
||||
const { server = "", secret = "" } = clashInfo;
|
||||
const wsUrl = buildWSUrl(server, secret, logLevel);
|
||||
|
||||
let isActive = true;
|
||||
const socket = createSockette(wsUrl, {
|
||||
onmessage(event) {
|
||||
if (!isActive) return;
|
||||
const data = JSON.parse(event.data) as ILogItem;
|
||||
const time = dayjs().format("MM-DD HH:mm:ss");
|
||||
appendLog({ ...data, time });
|
||||
},
|
||||
onerror() {
|
||||
if (!isActive) return;
|
||||
socket.close();
|
||||
},
|
||||
});
|
||||
|
||||
return () => {
|
||||
isActive = false;
|
||||
socket.close();
|
||||
};
|
||||
}, [clashInfo, enableLog, logLevel]);
|
||||
|
||||
// 根据当前选择的日志等级过滤日志
|
||||
return logLevel === "all"
|
||||
? logs
|
||||
: logs.filter((log) => log.type.toLowerCase() === logLevel);
|
||||
};
|
||||
|
||||
// 导出清空日志的方法
|
||||
export const clearLogs = () => {
|
||||
useLogStore.getState().clearLogs();
|
||||
};
|
||||
export const clearLogs = clearGlobalLogs;
|
||||
|
||||
Reference in New Issue
Block a user