UNPKG

mm_os

Version:

这是超级美眉服务端框架,用于快速构建应用程序。

169 lines (156 loc) 3.5 kB
/** * 日志类 */ class Log { /** * 构造函数 * @param {Object} config 配置参数 */ constructor(config) { this.config = { filename: '/log/output.log', console: false }; this.init(config); } } /** * 初始化 * @returns {Object} 配置参数 */ Log.prototype.init = function(config) { Object.assign(this.config, config); this.config.filename.addDir(); } /** * 清空日志 * @returns {String} 返回日志内容 */ Log.prototype.clear = function() { var file = this.config.filename; if(file.hasFile()){ file.delFile(); return true; } return false; } /** * 加载日志 * @returns {String} 返回日志内容 */ Log.prototype.load = function() { return this.config.filename.loadText() || ""; } /** * 保存日志 * @param {String} text 日志 */ Log.prototype.save = function(text) { return this.config.filename.saveText(text); } /** * 读取日志指定条 * @param {Number} index 索引,默认为最后一条 */ Log.prototype.read = function(index = -1) { var text = this.load(); var arr = text.split(/\n\[/); if (index < 0) { index = arr.length - 1; } var str = arr[index]; if (index == 0) { return str; } return "[" + str; } /** * 获取日志列表 * @returns {Array} 返回日志列表 */ Log.prototype.list = function() { var text = this.load(); var arr = text.split(/\n\[/); return arr.map((str, i) => { if (i == 0) { return str; } return "[" + str; }); } /** * 添加日志 * @param {String} type 日志类型 * @param {String} tag 日志标签 * @param {Object} arg 其他要输出的信息 */ Log.prototype.add = function(type, tag, ...arg) { var now = new Date(); var datetime = now.toStr('yyyy-MM-dd hh:mm:ss'); var list = new Array(arg); var content = ""; for (var i = 0; i < list.length; i++) { var o = list[i]; content += " " + o.toString(); } var str = `\n[${datetime}] [${type}] ${tag} -` + content; var text = this.load(); text += str; this.save(text.trim()); } /** * @description 信息 * @param {String} tag 日志标签 * @param {Object} arg 其他要输出的信息 */ Log.prototype.debug = function(tag, ...arg) { if (this.config.console) { console.log(tag, ...arg); } this.add('debug', tag, ...arg); }; /** * @description 信息 * @param {String} tag 日志标签 * @param {Object} arg 其他要输出的信息 */ Log.prototype.info = function(tag, ...arg) { if (this.config.console) { console.info(tag.blue, ...arg); } this.add('info', tag, ...arg); }; /** * @description 信息 * @param {String} tag 日志标签 * @param {Object} arg 其他要输出的信息 */ Log.prototype.warn = function(tag, ...arg) { if (this.config.console) { console.warn(tag.yellow, ...arg); } this.add('warn', tag, ...arg); }; /** * @description 信息 * @param {String} tag 日志标签 * @param {Object} arg 其他要输出的信息 */ Log.prototype.error = function(tag, ...arg) { if (this.config.console) { console.error(tag.red, ...arg); } this.add('error', tag, ...arg); }; /** * @description 成功 * @param {String} tag 日志标签 * @param {Object} arg 其他要输出的信息 */ Log.prototype.success = function(tag, ...arg) { if (this.config.console) { console.success(tag.green, ...arg); } this.add('debug', tag, ...arg); }; module.exports = Log;