File size: 4,071 Bytes
dd27eb1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
import fs from 'fs';

// 日志级别枚举
export const LogLevel = {
  DEBUG: 'DEBUG',
  INFO: 'INFO',
  WARN: 'WARN',
  ERROR: 'ERROR'
};

// 日志配置
const LOG_CONFIG = {
  logFile: './logs/app.log',
  logDir: './logs',
  enableConsole: true,
  enableFile: true,
  logLevel: LogLevel.INFO
};

/**
 * 确保日志目录存在
 */
function ensureLogDirectory() {
  if (!fs.existsSync(LOG_CONFIG.logDir)) {
    fs.mkdirSync(LOG_CONFIG.logDir, { recursive: true });
  }
}

/**
 * 格式化日志消息
 * @param {...any} args - 要记录的参数
 * @returns {string} 格式化后的消息
 */
function formatMessage(...args) {
  return args.map(arg =>
    typeof arg === 'object' ? JSON.stringify(arg) : String(arg)
  ).join(' ');
}

/**
 * 写入日志到文件
 * @param {string} level - 日志级别
 * @param {string} message - 日志消息
 */
function writeToFile(level, message) {
  if (!LOG_CONFIG.enableFile) return;

  ensureLogDirectory();
  const timestamp = new Date().toISOString();
  const logEntry = `[${timestamp}] [${level}] ${message}\n`;

  try {
    fs.appendFileSync(LOG_CONFIG.logFile, logEntry);
  } catch (error) {
    // 避免循环调用,直接使用console
    console.error('写入日志文件失败:', error);
  }
}

/**
 * 输出到控制台
 * @param {string} level - 日志级别
 * @param {...any} args - 要记录的参数
 */
function writeToConsole(level, ...args) {
  if (!LOG_CONFIG.enableConsole) return;

  switch (level) {
    case LogLevel.DEBUG:
      console.debug(...args);
      break;
    case LogLevel.INFO:
      console.log(...args);
      break;
    case LogLevel.WARN:
      console.warn(...args);
      break;
    case LogLevel.ERROR:
      console.error(...args);
      break;
    default:
      console.log(...args);
  }
}

/**
 * 通用日志记录函数
 * @param {string} level - 日志级别
 * @param {...any} args - 要记录的参数
 */
function writeLog(level, ...args) {
  const message = formatMessage(...args);

  // 输出到控制台
  writeToConsole(level, ...args);

  // 写入文件
  writeToFile(level, message);
}

/**
 * DEBUG级别日志
 * @param {...any} args - 要记录的参数
 */
export function debug(...args) {
  writeLog(LogLevel.DEBUG, ...args);
}

/**
 * INFO级别日志(替代console.log)
 * @param {...any} args - 要记录的参数
 */
export function info(...args) {
  writeLog(LogLevel.INFO, ...args);
}

/**
 * WARN级别日志(替代console.warn)
 * @param {...any} args - 要记录的参数
 */
export function warn(...args) {
  writeLog(LogLevel.WARN, ...args);
}

/**
 * ERROR级别日志(替代console.error)
 * @param {...any} args - 要记录的参数
 */
export function error(...args) {
  writeLog(LogLevel.ERROR, ...args);
}

/**
 * 读取最近的日志
 * @param {number} lines - 要读取的行数,默认100行
 * @returns {Array} 日志行数组
 */
export function getRecentLogs(lines = 100) {
  try {
    if (!fs.existsSync(LOG_CONFIG.logFile)) {
      return [];
    }

    const content = fs.readFileSync(LOG_CONFIG.logFile, 'utf8');
    const logLines = content.trim().split('\n').filter(line => line.length > 0);

    // 返回最后 N 行
    return logLines.slice(-lines);
  } catch (err) {
    console.error('读取日志文件失败:', err);
    return [];
  }
}

/**
 * 清空日志文件
 * @returns {boolean} 是否成功清空
 */
export function clearLogFile() {
  try {
    ensureLogDirectory();
    fs.writeFileSync(LOG_CONFIG.logFile, '');
    info('日志文件已清空');
    return true;
  } catch (err) {
    error('清空日志文件失败:', err);
    return false;
  }
}

/**
 * 配置日志设置
 * @param {Object} config - 日志配置
 */
export function configureLogger(config = {}) {
  Object.assign(LOG_CONFIG, config);
}

// 为了向后兼容,导出原有的函数名
export const log = info;
export const logError = error;

// 默认导出logger对象
export default {
  debug,
  info,
  warn,
  error,
  log: info,
  logError: error,
  getRecentLogs,
  clearLogFile,
  configureLogger,
  LogLevel
};