Search code examples
javascriptazureazure-application-insightsappinsights

Collect JavaScript console messages in App Insights


JavaScript console object provides many ways to output messages to a browser console:

console.log
console.error
console.warn
console.info
console.trace

By default Application Insights does not send console messages as telemetry to Azure Portal (Sending telemetry to the Azure portal) so my question is: What are the ways to capture console messages as telemetry in Application Insights?

Thank you


Solution

  • The best way to do this is probable going to be to override the console functions themselves. There is an existing answer that describes how to do this: Override console.log(); for production

    Keep in mind, that with custom implementation for App Insights, you'll usually want to use an npm installation instead of the App Insights code snippet to setup App Insights.

    The result might look like something like this:

    // define a new console
    var console=(function(oldCons){
        return {
            log: function(text){
                oldCons.log(text);
                telemetry.TrackTrace(text, SeverityLevel.Warning);
            },
            //override other console methods
        };
    }(window.console));
    
    //Then redefine the old console
    window.console = console;