如何远程调试console.log

时间:2017-04-23 18:49:24

标签: javascript angularjs ionic-framework remote-debugging

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

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

这是一个Q& A风格的问题,这意味着我将在下面提供答案,因为我觉得它对很多人来说非常有用。

1 个答案:

答案 0 :(得分:3)

该解决方案是您的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));
}
?>

快乐的调试!