js 封装日志上传模块,实现异常日志的上报

封装定义日志上传模块,实现异常日志的上报,包含触发方式:

1、主动调取方法上报

2、覆盖原生console.error实现,收集所有console.error打印的日志

3、window注册绑定error事件,触发 window.addEventListener('error',

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
/**
 * 客户端日志上传模块,实现异常日志的上报
 * 使用时在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);
    };
  }
})();

  

posted @   Gaochunling  阅读(43)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示