Wednesday, November 9, 2016

AngularJS - JavaScript - Client Side error logging

Usually for ServerSide logging we can use many error logging tools (For ex: elmah, log4net etc.,) to log errors into database and email. But for client side JavaScript framework we should include some extra code or some tools available (for ex: JSNLog etc.,). Here am going to explain how custom we do that,

First create JavaScript file "errorlog.js" and copy paste below code,

var errorLoggingServerURL = "Error/Log";

function logErrorToServer(ex, stack) {
    if (ex == null) return;

    if (stack == null && ex.stack != null) stack = ex.stack;

    // format output
    var out = ex.message != null ? ex.name + ": " + ex.message : "JavaScript Exception";
    if (stack != null) out += "\n  at " + stack.toString();

   
    // send error message
    $.ajax({
        type: 'POST',
        url: errorLoggingServerURL,
        data: { message: escape(out) }
    });

}

Function.prototype.trace = function () {
    var trace = [];
    var current = this;
    while (current) {
        trace.push(current.signature());
        current = current.caller;
    }
    return trace;
}

Function.prototype.signature = function () {
    var signature = {
        name: this.getName(),
        params: [],
        toString: function () {
            var params = this.params.length > 0 ?
                "'" + this.params.join("', '") + "'" : "";
            return this.name + "(" + params + ")"
        }
    };
    if (this.arguments) {
        for (var x = 0; x < this.arguments.length; x++)
            signature.params.push(this.arguments[x]);
    }
    return signature;
}

Function.prototype.getName = function () {
    if (this.name)
        return this.name;
    var definition = this.toString().split("\n")[0];
    var exp = /^function ([^\s(]+).+/;
    if (exp.test(definition))
        return definition.split("\n")[0].replace(exp, "$1") || "anonymous";
    return "anonymous";
}

window.onerror = function (msg, url, line) {
    if (arguments != null && arguments.callee != null && arguments.callee.trace)
        logErrorToServer(msg, arguments.callee.trace());

}


In AngularJS, we can have custom logging as follows,

To override AngularJS default logging and to write custom logging use as below,

 app.factory('$exceptionHandler', function () {
        return function (exception, cause) {
            //Javascript Error log will catch this
            logErrorToServer(exception);
        };
    })

Or to use both angularJS default logging and custom logging use as below

//Exception log decorator
 $provide.decorator('$exceptionHandler', ['$delegate', function ($delegate) {
    return function (exception, cause) {
     $delegate(exception, cause);
     logErrorToServer(exception);
    };
 }]);



In Server Side, we can receive the Ajax call and use any logging tool to log error, For ex, here am using Elmah to log error, it uses MVC action controller and using logging as custom class named JavaScriptException

public class ErrorController : Controller
    {
public void Log(string message)
        {
            ErrorSignal
                .FromCurrentContext()
                .Raise(new JavaScriptException(HttpUtility.UrlDecode(message)));
     }

   }

No comments:

Post a Comment