实现效果:
定时或者日志满足多少条之后,自动将控制台的 某个等级的错误日志 生成txt(当然也可以是其他的文件,完全自定义) 内容包含 日志时间、日志内容,日志的堆栈来源(这个是使用 new Error(日志内容) 所以 日志堆栈的实现 还有提升空间)
话不多说 往下看===>
原理:
(这块当然完全可以自定义,根据自己的需求 进行修改方法,可以仿照思路)
首先使用自己封装的方法,来获取日志内容,判断console对象下是否已经存在自己复制的方法;
然后自己复制一份方法到 console 对象下 以old为前缀,再覆盖原本的方法,原本的方法中 再调用 old备份的方法;
后面的两个判断 是维护的 数组中大于100条之后,就生成文件或者 不足 100条的情况下 最长时间 一天打印一次(如果说自己的软件 存在超时登录的这种机制,自己的时间 可以再次调整);
实现过程:
/*存储并且打印日志
logLevel:日志等级 支持console下所有对象
*/
getLog(logLevel) {
if(logLevel === 'trace') return;
if(console[ 'old'+logLevel] == undefined) console[ 'old'+logLevel] = console[logLevel];
console[logLevel] = (str) => {
console.trace("str===========>",str);
try {
console[ 'old'+logLevel](str);
} catch (e) {
}
let message = window.vue.$GlobalFuc.formatDate(new Date(),'yyyy-MM-dd hh:mm:ss') + '--' + str +