|
1 | | -import colors from 'picocolors' |
2 | | - |
3 | 1 | class Logger { |
4 | | - constructor(command) { |
| 2 | + constructor(command = 'default') { |
5 | 3 | this.command = command |
| 4 | + this.hasColors = this.checkColorSupport() |
6 | 5 | } |
7 | 6 |
|
8 | | - output(type, msg) { |
9 | | - const format = () => { |
| 7 | + checkColorSupport() { |
| 8 | + try { |
| 9 | + require('colors') |
| 10 | + return true |
| 11 | + } catch (e) { |
| 12 | + console.warn('colors package not found, using basic logging') |
| 13 | + return false |
| 14 | + } |
| 15 | + } |
| 16 | + |
| 17 | + output(type, ...args) { // 支持多个参数 |
| 18 | + const time = new Date().toLocaleTimeString() |
| 19 | + const prefix = `[${this.command}] [${time}]` |
| 20 | + |
| 21 | + // 将所有参数合并为一个字符串 |
| 22 | + const message = args.map(arg => { |
| 23 | + if (typeof arg === 'object') { |
| 24 | + return JSON.stringify(arg, null, 2) |
| 25 | + } |
| 26 | + return String(arg) |
| 27 | + }).join(' ') |
| 28 | + |
| 29 | + if (this.hasColors) { |
| 30 | + const colors = require('colors') |
10 | 31 | const colorMap = { |
11 | | - info: 'cyan', |
12 | | - warn: 'yellow', |
13 | | - error: 'red', |
14 | | - success: 'green' |
| 32 | + info: colors.cyan, |
| 33 | + warn: colors.yellow, |
| 34 | + error: colors.red, |
| 35 | + success: colors.green |
15 | 36 | } |
16 | | - const time = new Date().toLocaleTimeString() |
17 | | - const colorMsg = colors[colorMap[type]](type) |
18 | 37 |
|
19 | | - return `[${this.command}] [${colors.dim(time)}] ${colorMsg} ${msg}` |
| 38 | + const coloredType = colorMap[type] ? colorMap[type](type.toUpperCase()) : type.toUpperCase() |
| 39 | + console.log(`${prefix} ${coloredType} ${message}`) |
| 40 | + } else { |
| 41 | + const emojiMap = { |
| 42 | + info: 'ℹ️', |
| 43 | + warn: '⚠️', |
| 44 | + error: '❌', |
| 45 | + success: '✅' |
| 46 | + } |
| 47 | + console.log(`${prefix} ${emojiMap[type] || ''} ${message}`) |
20 | 48 | } |
21 | | - const _logger = console |
22 | | - |
23 | | - return _logger.log(format()) |
24 | 49 | } |
25 | 50 |
|
26 | | - info(msg) { |
27 | | - this.output('info', msg) |
| 51 | + success(...args) { |
| 52 | + this.output('success', ...args) |
28 | 53 | } |
29 | 54 |
|
30 | | - warn(msg) { |
31 | | - this.output('warn', msg) |
| 55 | + info(...args) { |
| 56 | + this.output('info', ...args) |
32 | 57 | } |
33 | 58 |
|
34 | | - error(msg) { |
35 | | - this.output('error', msg) |
| 59 | + warn(...args) { |
| 60 | + this.output('warn', ...args) |
36 | 61 | } |
37 | 62 |
|
38 | | - success(msg) { |
39 | | - this.output('success', msg) |
| 63 | + error(...args) { |
| 64 | + this.output('error', ...args) |
40 | 65 | } |
41 | 66 | } |
42 | | - |
43 | 67 | export default Logger |
0 commit comments