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);
|
}
|
}
|