【问题标题】:How to remote debug console.log如何远程调试console.log
【发布时间】:2017-09-20 08:52:30
【问题描述】:

问题:在开发 Ionic2 应用程序时,我想查看我的 iPhone 上生成的 console.log 消息,但我没有 Mac,或者我有但发现网络检查器功能很糟糕。

请注意,这适用于任何类型的远程 javascript,不仅适用于 Angular/ionic。

这是一个问答式的问题,这意味着我将在下面提供答案,因为我认为它对很多人都非常有用。

【问题讨论】:

    标签: javascript angularjs ionic-framework remote-debugging


    【解决方案1】:

    解决方案是一个挂钩到您的 javascript 中,它将拦截所有 console.log 和错误并将它们发送到服务器。

    将以下代码放入您的 index.html 页面:

    <script>
    // Function that will call your webserver
    logToServer = function(consoleMsg) {
        // only do this if on device
        if (window.cordova) {
            let jsonTxt = customStringify(consoleMsg);
            var xmlHttp = new XMLHttpRequest();
            xmlHttp.open("GET", 'http://yourserver/console2server.php?msg=' + jsonTxt, true); //async
            xmlHttp.send(null);
        }
    }
    
    // Test if you receive this on the server
    logToServer("OPENING IONIC APP");
    
    // intercept console logs
    (function () {
        var oldLog = console.log;
        console.log = function (message) {
            // DO MESSAGE HERE.
            logToServer(message);
            oldLog.apply(console, arguments);
        };
    })();
    
    // intecept errors
    if (window && !window.onerror) {
        window.onerror = function (errorMsg, url, lineNumber, column, errorObj) {
            logToServer(errorMsg);
            logToServer(errorObj);
            return false;
        }
    }
    
    // this is optional, but it avoids 'converting circular structure' errors
    customStringify = function (inp) {
        return JSON.stringify(inp, function (key, value) {
            if (typeof value === 'object' && value !== null) {
                if (cache.indexOf(value) !== -1) {
                    // Circular reference found, discard key
                    console.log("circular dep found!!");
                    return;
                }
                // Store value in our collection
                cache.push(value);
            }
            return value;
        });
    }
    </script>
    

    在服务器端,我使用 PHP,但你可以使用任何你想要的:

    <?php
    //allow CORS request
    header('Access-Control-Allow-Origin: *');
    
    if(isset($_GET['msg'])) {
        //you can also log to a file or whatever, I just log to standard logs
        error_log("[CONSOLE.LOG] ".json_decode($_GET['msg'], true));
    }
    ?>
    

    调试愉快!

    【讨论】:

      猜你喜欢
      • 2023-03-20
      • 2014-03-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-26
      • 1970-01-01
      • 2018-05-06
      • 2015-03-19
      相关资源
      最近更新 更多