【sdk封装】前端错误日志采集

ec-sdk.js

// 基于window.onerror 收集前端错误信息
window.onerror = function(message, url, line) {
    if (!url) return;

    var msg = {};

    //记录客户端环境
    msg.ua = window.navigator.userAgent;

    //只记录message里的message属性就好了,
    //错误信息可能会比较晦涩,有些信息完全无用,应酌情过滤
    msg.message = message;
    msg.url = url;
    msg.line = line;
    msg.page = window.location.href;

    var s = [];

    //将错误信息转换成字符串
    for(var key in msg){
        s.push(key + '=' + msg[key]);
    }

    s = s.join('&');
    
    console.log('msg',msg);
    console.log('msg',JSON.stringify(msg));
    //控制台打印
    var log_msg =  {
        "ua":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.129 Safari/537.36",
        "message":"Uncaught ReferenceError: a is not defined",
        "url":"file:///C:/Users/ymtt/Desktop/%E5%89%8D%E7%AB%AFbasics/%E5%89%8D%E7%AB%AF%E5%BC%82%E5%B8%B8%E7%9B%91%E6%8E%A7/ec-demo.html",
        "line":11,
        "page":"file:///C:/Users/ymtt/Desktop/%E5%89%8D%E7%AB%AFbasics/%E5%89%8D%E7%AB%AF%E5%BC%82%E5%B8%B8%E7%9B%91%E6%8E%A7/ec-demo.html"
    }

    //这里是用增加标签的方法调用日志收集接口,优点是比较简洁。
    // new Image().src = '/ajax-jserror.php?' + encodeURIComponent(s) + '&t=' + Math.random();   

};

 

ec-demo.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ec-demo</title>
    <script src="./ec-sdk.js"></script>
</head>
<body>
<script>
     console.log('a',a);
</script>
</body>
</html>

 

posted @ 2020-05-06 18:02  expworld  阅读(438)  评论(0编辑  收藏  举报