58 lines
1.6 KiB
TypeScript
58 lines
1.6 KiB
TypeScript
// ZCLAW 日志系统
|
|
type LogLevel = 'debug' | 'info' | 'warn' | 'error';
|
|
|
|
const LEVEL_PRIORITY: Record<LogLevel, number> = {
|
|
debug: 0,
|
|
info: 1,
|
|
warn: 2,
|
|
error: 3,
|
|
};
|
|
|
|
const LEVEL_COLORS: Record<LogLevel, string> = {
|
|
debug: '\x1b[36m', // cyan
|
|
info: '\x1b[32m', // green
|
|
warn: '\x1b[33m', // yellow
|
|
error: '\x1b[31m', // red
|
|
};
|
|
|
|
const RESET = '\x1b[0m';
|
|
|
|
let currentLevel: LogLevel = 'info';
|
|
|
|
export function setLogLevel(level: LogLevel): void {
|
|
currentLevel = level;
|
|
}
|
|
|
|
function shouldLog(level: LogLevel): boolean {
|
|
return LEVEL_PRIORITY[level] >= LEVEL_PRIORITY[currentLevel];
|
|
}
|
|
|
|
function formatTimestamp(): string {
|
|
return new Date().toISOString().slice(11, 23);
|
|
}
|
|
|
|
function log(level: LogLevel, module: string, message: string, data?: any): void {
|
|
if (!shouldLog(level)) return;
|
|
|
|
const color = LEVEL_COLORS[level];
|
|
const timestamp = formatTimestamp();
|
|
const prefix = `${color}[${timestamp}] [${level.toUpperCase()}] [${module}]${RESET}`;
|
|
|
|
if (data !== undefined) {
|
|
console.log(`${prefix} ${message}`, typeof data === 'object' ? JSON.stringify(data, null, 2) : data);
|
|
} else {
|
|
console.log(`${prefix} ${message}`);
|
|
}
|
|
}
|
|
|
|
export function createLogger(module: string) {
|
|
return {
|
|
debug: (message: string, data?: any) => log('debug', module, message, data),
|
|
info: (message: string, data?: any) => log('info', module, message, data),
|
|
warn: (message: string, data?: any) => log('warn', module, message, data),
|
|
error: (message: string, data?: any) => log('error', module, message, data),
|
|
};
|
|
}
|
|
|
|
export type Logger = ReturnType<typeof createLogger>;
|