封装定义日志上传模块,实现异常日志的上报,包含触发方式:
1、主动调取方法上报
2、覆盖原生console.error实现,收集所有console.error打印的日志
3、window注册绑定error事件,触发 window.addEventListener('error',
/** * 客户端日志上传模块,实现异常日志的上报 * 使用时在HTML文档<head>的最前面通过<script>标签引入即可 * 项目各自修改对应的log.png的存放位置 */ (function () { var errorLog = console.error; var LOG_URL = '//' + document.location.host + '/img/log.png?d='; //可以配置的服务端日志采集接口,暂时使用固定图片代替 document.location.host '127.0.0.1:3009/' function logImg(s) { var img = new Image(1, 1); img.src = s; img.onerror = function (err) { console.log(err); img = null; errorLog('[ERROR]日志上报失败', s); }; img.onload = function () { img = null; }; } function sendSvrLog() { var args = [].slice.call(arguments, 0); var ans = []; for (var i = 0, len = args.length; i < len; i++) { ans.push(typeof args[i] === 'string' ? args[i] : (args[i].stack || JSON.stringify(args[i]))); } var msg = ans.join('\n').replace(/[\t\r\n<]/g, ' '); for (var i = 0; i < msg.length; i += 4000) { logImg(LOG_URL + Date.now() + ':' + (i + 1) + ':' + msg.slice(i, i + 4000)); } } console.error = function () { //覆盖原生console.error实现,收集所有console.error打印的日志. errorLog.apply(console, arguments); sendSvrLog.apply(null, arguments); }; window._sendSvrLog = function (e) { console.log(e); sendSvrLog(e.stack); }; //window.onerror = sendSvrLog; if ('addEventListener' in window) { window.addEventListener('error', function (e) { console.log(e); sendSvrLog(e.message || e.error.stack); }); } else { window.onerror = function (e) { console.log(e); sendSvrLog(e.message || e.stack); }; } })();
标签:function,封装,img,args,js,error,var,日志 From: https://www.cnblogs.com/litterjoan/p/18382882