@alova/wormhole
Version:
More modern openAPI generating solution for alova.js
77 lines (76 loc) • 2.6 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.logger = void 0;
const config_1 = require("../../config");
const DEFAULT_CONFIG = (0, config_1.getGlobalConfig)();
class Logger {
constructor() {
this.options = {
level: 'info',
timestamp: true,
colors: true,
};
}
configure(options) {
this.options = { ...this.options, ...options };
return this;
}
getTimestamp() {
return this.options.timestamp ? `[${new Date().toISOString()}] ` : '';
}
formatMessage(level, message, details) {
const timestamp = this.getTimestamp();
const prefix = this.options.prefix ? `[${this.options.prefix}] ` : '';
const detailsStr = details ? `\n${JSON.stringify(details, null, 2)}` : '';
if (this.options.colors) {
const colors = {
debug: '\x1B[34m', // blue
info: '\x1B[32m', // green
warn: '\x1B[33m', // yellow
error: '\x1B[31m', // red
reset: '\x1B[0m',
};
return `${timestamp}${prefix}${colors[level]}[${level.toUpperCase()}]${colors.reset} ${message}${detailsStr}`;
}
return `${timestamp}${prefix}[${level.toUpperCase()}] ${message}${detailsStr}`;
}
shouldLog(level) {
const levels = ['debug', 'info', 'warn', 'error'];
return levels.indexOf(level) >= levels.indexOf(this.options.level);
}
debug(message, details) {
if (this.shouldLog('debug')) {
// eslint-disable-next-line no-console
console.debug(this.formatMessage('debug', message, details));
}
}
info(message, details) {
if (this.shouldLog('info')) {
// eslint-disable-next-line no-console
console.info(this.formatMessage('info', message, details));
}
}
warn(message, details) {
if (this.shouldLog('warn')) {
console.warn(this.formatMessage('warn', message, details));
}
}
errorMsg(msg) {
return msg instanceof Error ? msg.message : msg;
}
error(message, details) {
if (this.shouldLog('error')) {
console.error(this.formatMessage('error', message, details));
}
}
throwError(error, details) {
this.debug(this.errorMsg(error), details);
return new DEFAULT_CONFIG.Error(this.errorMsg(error));
}
}
// 导出单例实例
exports.logger = new Logger().configure({
level: 'info',
timestamp: true,
colors: true,
});