const util = require('util'); const config = require('../config'); // ANSI 颜色代码 const colors = { reset: "\x1b[0m", bright: "\x1b[1m", dim: "\x1b[2m", underscore: "\x1b[4m", blink: "\x1b[5m", reverse: "\x1b[7m", hidden: "\x1b[8m", fg: { black: "\x1b[30m", red: "\x1b[31m", green: "\x1b[32m", yellow: "\x1b[33m", blue: "\x1b[34m", magenta: "\x1b[35m", cyan: "\x1b[36m", white: "\x1b[37m", gray: "\x1b[90m", }, bg: { black: "\x1b[40m", red: "\x1b[41m", green: "\x1b[42m", yellow: "\x1b[43m", blue: "\x1b[44m", magenta: "\x1b[45m", cyan: "\x1b[46m", white: "\x1b[47m", } }; function formatTime() { const now = new Date(); const timeStr = now.toLocaleTimeString('zh-CN', { hour12: false }); const ms = String(now.getMilliseconds()).padStart(3, '0'); return `${timeStr}.${ms}`; } const logger = { // 普通信息 - 青色标签 info: (category, message, ...args) => { if (!config.enableLog) return; const time = `${colors.fg.gray}[${formatTime()}]${colors.reset}`; const tag = `${colors.fg.cyan}[${category}]${colors.reset}`; console.log(`${time} ${tag} ${message}`, ...args); }, // 成功信息 - 绿色标签 success: (category, message, ...args) => { if (!config.enableLog) return; const time = `${colors.fg.gray}[${formatTime()}]${colors.reset}`; const tag = `${colors.fg.green}[${category}]${colors.reset}`; console.log(`${time} ${tag} ${message}`, ...args); }, // 警告信息 - 黄色标签 warn: (category, message, ...args) => { if (!config.enableLog) return; const time = `${colors.fg.gray}[${formatTime()}]${colors.reset}`; const tag = `${colors.fg.yellow}[${category}]${colors.reset}`; console.warn(`${time} ${tag} ${message}`, ...args); }, // 错误信息 - 红色标签 error: (category, message, ...args) => { if (!config.enableLog) return; const time = `${colors.fg.gray}[${formatTime()}]${colors.reset}`; const tag = `${colors.fg.red}[${category}]${colors.reset}`; console.error(`${time} ${tag} ${message}`, ...args); }, // 调试信息 - 洋红色标签 (对象会自动展开) debug: (category, message, ...args) => { if (!config.enableLog) return; const time = `${colors.fg.gray}[${formatTime()}]${colors.reset}`; const tag = `${colors.fg.magenta}[${category}]${colors.reset}`; // 使用 util.inspect 格式化对象,使其带有颜色且深度无限 const formattedArgs = args.map(arg => (typeof arg === 'object' && arg !== null) ? '\n' + util.inspect(arg, { colors: true, depth: null, breakLength: 80 }) : arg ); console.log(`${time} ${tag} ${message}`, ...formattedArgs); }, // 分割线 - 用于区分请求 divider: (title) => { if (!config.enableLog) return; console.log(`${colors.fg.gray}----------------------------------------------------------------${colors.reset}`); if (title) { console.log(`${colors.fg.white}${colors.bright}👉 ${title}${colors.reset}`); } } }; module.exports = logger;