UNPKG

tencentcloud-edgeone-migration-nodejs-v2

Version:

tencentcloud cdn config copy to edgeone

113 lines (98 loc) 2.6 kB
const fs = require('fs'); const path = require('path'); const logger = require('./src/logger'); const LogType = { INFO: 'info', SUCCESS: 'success', ERROR: 'error', WARN: 'warn' }; class LogGenerator { constructor() { this.messageList = []; } static getInstance() { if (!LogGenerator.instance) { LogGenerator.instance = new LogGenerator(); } return LogGenerator.instance; } printMsg(msg, type) { if(Array.isArray(msg)) { msg.forEach(msg => { logger[type](msg); }); } else { logger[type](msg); } } pushMsg(message) { if (Array.isArray(message)) { this.messageList = this.messageList.concat( message.map(msg => ({ message: msg, isoTime: new Date().toISOString() })) ); } else { this.messageList.push({ message, isoTime: new Date().toISOString() }); } } defaultLog(msg) { this.pushMsg(msg); this.printMsg(msg, LogType.INFO); } successLog(msg) { this.pushMsg(msg); this.printMsg(msg, LogType.SUCCESS); } errorLog(msg) { this.pushMsg(msg); this.printMsg(msg, LogType.ERROR); } warnLog(msg) { this.pushMsg(msg); this.printMsg(msg, LogType.WARN); } throwError(msg) { this.pushMsg(msg); throw new Error(msg); } fetchLog(action, {payload, response}) { if(payload) { const payloadMsg = `Fetch ${action}: \nRequest Payload: ${JSON.stringify(payload)}`; this.pushMsg(payloadMsg); } if(response) { const resMsg = `${action} response: ${JSON.stringify(response)}` this.pushMsg(resMsg); } } writeLogFile(fileName) { return new Promise((resolve, reject) => { const logDir = path.join(__dirname, './logs'); const sanitizedFileName = fileName.replace(/:/g, '_'); const logPath = path.join(logDir, `${sanitizedFileName}.log`); // 日志文件路径 const logMessage = this.messageList.map(({ message, isoTime }) => { return `[${isoTime}]: ${message}`; }); const logMessageStr = logMessage.join('\n'); if (!fs.existsSync(logDir)) { fs.mkdirSync(logDir); } // 异步写入日志 fs.appendFile(logPath, logMessageStr, { mode: 0o666 }, (err) => { if (err) { console.error('写入日志失败:', err); reject({result: 'failed', message: err}); } else { resolve({result: 'success', message: 'success to write log file'}); } }); }); } } module.exports = LogGenerator.getInstance();