wujingjing
2025-04-09 f17a10fa1490e4a1840997900770a43ce2ac7313
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
import { formatDate } from "/@/utils/formatTime";
 
export class Logger {
    static level = 'DEBUG'; // 默认为DEBUG级别
    static shouldLog(level) {
        const levels = ['DEBUG', 'INFO', 'WARN', 'ERROR', 'FATAL'];
        return levels.indexOf(level) >= levels.indexOf(this.level);
    }
 
    static formatStack(stack) {
        if (!stack) return '';
        // 格式化错误堆栈的逻辑
        return stack
            .split('\n')
            .map((line) => `    at ${line}`)
            .join('\n');
    }
    static log(level, message, error?) {
        const timestamp = formatDate(new Date());
        const stack = error ? `\n${this.formatStack(error.stack)}` : '';
 
        const formattedMessage = `[${timestamp}] [${level}] ${message} ${stack}`;
 
        switch (level) {
            case 'DEBUG':
                console.debug(formattedMessage);
                break;
            case 'INFO':
                console.info(formattedMessage);
                break;
            case 'WARN':
                console.warn(formattedMessage);
                break;
            case 'ERROR':
            case 'FATAL':
                console.error(formattedMessage);
                break;
            default:
                console.log(formattedMessage);
        }
    }
 
    //      // 根据环境变量判断是否发送日志到后端
    // if (process.env.NODE_ENV === 'production') {
    //     this.sendLog(formattedMessage);
    //   }
 
    // static sendLog(message) {
    //     // 假设我们有一个日志收集的API
    //     const logEndpoint = '/api/logs';
    //     fetch(logEndpoint, {
    //         method: 'POST',
    //         headers: {
    //             'Content-Type': 'application/json',
    //         },
    //         body: JSON.stringify({ message }),
    //     }).catch((error) => {
    //         console.error('Failed to send log', error);
    //     });
    // }
 
    static debug(message) {
        this.log('DEBUG', message);
    }
 
    static info(message) {
        this.log('INFO', message);
    }
 
    static warn(message) {
        this.log('WARN', message);
    }
 
    static error(message, error?) {
        this.log('ERROR', message, error);
    }
 
    static fatal(message, error?) {
        this.log('FATAL', message, error);
    }
}