码桶
发现社区成员的开源项目
logStore.ts1.6 KB
// 前端日志存储(非 React,可在 api.ts 等纯模块中使用)
// LogConsole 组件通过 subscribe 获取实时日志流
export type LogLevel = 'info' | 'warn' | 'error'
export type LogType = 'request' | 'response' | 'error' | 'system'
export interface LogEntry {
id: number
timestamp: number
type: LogType
level: LogLevel
method?: string
path?: string
status?: number
duration?: number
requestBody?: unknown
responseBody?: unknown
message: string
}
type Listener = (entry: LogEntry) => void
class LogStore {
private entries: LogEntry[] = []
private listeners = new Set<Listener>()
private nextId = 1
maxEntries = 500
add(partial: Omit<LogEntry, 'id' | 'timestamp'>) {
const entry: LogEntry = {
...partial,
id: this.nextId++,
timestamp: Date.now(),
}
this.entries.push(entry)
if (this.entries.length > this.maxEntries) {
this.entries = this.entries.slice(-this.maxEntries)
}
for (const fn of this.listeners) {
try { fn(entry) } catch { /* ignore listener errors */ }
}
}
getAll(): LogEntry[] {
return [...this.entries]
}
clear() {
this.entries = []
// 广播清空事件
const clearEntry: LogEntry = {
id: -1, timestamp: Date.now(), type: 'system', level: 'info', message: '__CLEAR__'
}
for (const fn of this.listeners) {
try { fn(clearEntry) } catch { /* ignore */ }
}
}
subscribe(fn: Listener): () => void {
this.listeners.add(fn)
return () => { this.listeners.delete(fn) }
}
}
export const logStore = new LogStore()