You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
86 lines
2.3 KiB
86 lines
2.3 KiB
// 日志记录模块,用于将控制台输出同时保存到文件
|
|
const fs = require('fs');
|
|
const path = require('path');
|
|
|
|
// 确保logs目录存在
|
|
const logsDir = path.join(__dirname, 'logs');
|
|
if (!fs.existsSync(logsDir)) {
|
|
fs.mkdirSync(logsDir);
|
|
}
|
|
|
|
// 获取当前日期,用于日志文件名
|
|
function getCurrentDate() {
|
|
const now = new Date();
|
|
const year = now.getFullYear();
|
|
const month = String(now.getMonth() + 1).padStart(2, '0');
|
|
const day = String(now.getDate()).padStart(2, '0');
|
|
return `${year}-${month}-${day}`;
|
|
}
|
|
|
|
// 获取带时区的时间戳
|
|
function getFormattedTimestamp() {
|
|
const now = new Date();
|
|
const beijingTime = new Date(now.getTime() + 8 * 60 * 60 * 1000);
|
|
return beijingTime.toISOString().replace('Z', '+08:00');
|
|
}
|
|
|
|
// 写入日志到文件
|
|
function writeLogToFile(level, message) {
|
|
const timestamp = getFormattedTimestamp();
|
|
const logMessage = `[${timestamp}] [${level}] ${message}\n`;
|
|
const logFilePath = path.join(logsDir, `server-${getCurrentDate()}.log`);
|
|
|
|
fs.appendFile(logFilePath, logMessage, (err) => {
|
|
if (err) {
|
|
console.error('写入日志文件失败:', err);
|
|
}
|
|
});
|
|
}
|
|
|
|
// 重写console.log,使其同时输出到控制台和文件
|
|
const originalConsoleLog = console.log;
|
|
const originalConsoleError = console.error;
|
|
const originalConsoleWarn = console.warn;
|
|
const originalConsoleInfo = console.info;
|
|
|
|
console.log = function (...args) {
|
|
const message = args.map(arg =>
|
|
typeof arg === 'object' ? JSON.stringify(arg) : String(arg)
|
|
).join(' ');
|
|
|
|
originalConsoleLog.apply(console, args);
|
|
writeLogToFile('INFO', message);
|
|
};
|
|
|
|
console.error = function (...args) {
|
|
const message = args.map(arg =>
|
|
typeof arg === 'object' ? JSON.stringify(arg) : String(arg)
|
|
).join(' ');
|
|
|
|
originalConsoleError.apply(console, args);
|
|
writeLogToFile('ERROR', message);
|
|
};
|
|
|
|
console.warn = function (...args) {
|
|
const message = args.map(arg =>
|
|
typeof arg === 'object' ? JSON.stringify(arg) : String(arg)
|
|
).join(' ');
|
|
|
|
originalConsoleWarn.apply(console, args);
|
|
writeLogToFile('WARN', message);
|
|
};
|
|
|
|
console.info = function (...args) {
|
|
const message = args.map(arg =>
|
|
typeof arg === 'object' ? JSON.stringify(arg) : String(arg)
|
|
).join(' ');
|
|
|
|
originalConsoleInfo.apply(console, args);
|
|
writeLogToFile('INFO', message);
|
|
};
|
|
|
|
module.exports = {
|
|
logsDir,
|
|
getFormattedTimestamp,
|
|
writeLogToFile
|
|
};
|