UNPKG

@plasosdk/plaso-electron-sdk

Version:

伯索课堂Electron SDK

139 lines (126 loc) 4.1 kB
const { LEVEL } = require('../js/macro'); const LEVEL_FORMAT_LENGTH = Math.max(...Object.keys(LEVEL).map((key) => key.length)) + 1; class LogFormatter { constructor(loggerPath) { this.loggerPath = loggerPath ? loggerPath.replace(/\\/g, '/') : ''; this.fs; this.util; this.newLogTime; this.ws = null; } init() { try { this.fs = window.require('fs'); this.util = window.require('util'); const process = window.require('process'); process.on('uncaughtException', (error) => this.write(LEVEL.error, error ? error.stack : {})); } catch (error) { console.error('log error', error); } } initLoggerFilePath(_loggerPath) { this.loggerPath = _loggerPath ? _loggerPath.replace(/\\/g, '/') : ''; } createWS() { if (this.fs && this.loggerPath && this.newLogTime) { this.logFileName = 'plasoElectronSdk_'; this.ws = this.fs.createWriteStream(`${this.loggerPath}/${this.logFileName}${this.newLogTime}.log`, { flags: 'a' }); this.ws.write(`Start log: ${new Date()}\n\n`); } } _writeLog(prefix, logContent) { if (this.ws) { this.ws.write(prefix); this.ws.write(logContent); this.ws.write('\n'); } } write(level, ...format) { try { if (!this.fs || !this.util) { return; } const today = new Date(); const newLogTime = `${today.getFullYear()}-${today.getMonth() + 1}-${today.getDate()}`; if (newLogTime !== this.newLogTime) { this.newLogTime = newLogTime; if (this.ws !== null) { this.ws.end(); this.ws = null; } } if (this.ws == null) { this.createWS(); } const maxContentSize = 10 * 1024; let logContent = this.util.format(...format); const logContentSize = logContent.length; // 单条日志长度超过10K则进行截取 if (logContentSize > maxContentSize) { logContent = logContent.slice(0, maxContentSize) + ` <<< more (${((logContentSize - maxContentSize) / 1024).toFixed(1)}KB)`; } const logTime = `[${today.toLocaleTimeString('en-US', { hour12: false })}.${today .getMilliseconds() .toString() .padStart(3, '0')}]`; let logLevel = ''; switch (level) { case LEVEL.ERROR: logLevel = 'ERROR'; break; case LEVEL.WARN: logLevel = 'WARN'; break; case LEVEL.INFO: logLevel = 'INFO'; break; case LEVEL.DEBUG: logLevel = 'DEBUG'; break; } const prefix = `${logLevel.padEnd(LEVEL_FORMAT_LENGTH, ' ')} ${logTime} `; this._writeLog(prefix, logContent); } catch (e) { console.error('log write error', e); } } /** * @param {any[]} content */ info(...content) { this.log('info', ...content); } /** * @param {any[]} content */ debug(...content) { this.log('debug', ...content); } /** * @param {any[]} content */ warn(...content) { this.log('warn', ...content); } /** * @param {any[]} content */ error(...content) { this.log('error', ...content); } /** * @private * @param {'info' | 'debug' | 'error' | 'warn'} level * @param {any[]} content */ log(level, ...content) { if (this.loggerPath) { this.write(LEVEL[level], ...content); } else { console[level](...content); } } } module.exports = LogFormatter;