Error Logging with Elmah & JSNLog : Javascript exception logger to log exceptions on server side log.


Since longtime, I was logging server side exceptions using log4net in all my asp.net web sites. Now I was using “console.log” extensively for debug purpose and logging purpose. BUT there was not known method to me at least which can log the client side errors & info etc. to same server side logging engine, until I learnt JSNLog…. 

Summary: What is jsnlog anyways ?

JSNLog lets you insert loggers in your client side JavaScript, configure them in your web.config, and store their messages in your server side logs.

Why there is a need ?

Using your server side logging package, such as Log4Net, NLog or Elmah, with loggers configured via web.config,

try
{
    ....
}
catch (Exception e)
{
    ILog log = LogManager.GetLogger("serverlogger");
    log.Fatal(e.ToString());
}

 

but how can we merge client side javascript try-catch exceptions to these server side logging engines ?

JavaScript: 
try { .... } catch(err) { ???? }

But what about exceptions in your JavaScript code?

JSNLog will pass the JavaScript exception log message with its stack trace on to your server side logging package, so it winds up in your server side logs. You can log extra information, such as the values of variables.

 

try
{
    ....
}
catch(e)
{
    // Log the exception, complete with stack trace
    JL("jsLogger").fatalException({ "msg": "something went wrong!", "variable1": variable1, ... }, e);
}

 or we can always write master function using window.onerror () in javascript , like – 

window.onerror = function (errorMsg, url, lineNumber, column, errorObj) {
    JL("onerrorLogger").fatalException({
        "msg": "something went wrong!", 
        "errorMsg": errorMsg, "url": url, 
        "line number": lineNumber, "column": column
    }, errorObj);
        
    return false;
}

Benefits

  • Extensive documentation. Easy to install.
  • No need to pay fees to a third party logging service.
  • JavaScript log messages go into the same logs as your server side log messages.
  • Or send JavaScript log messages to the browser console.
  • Uses a tiny JavaScript library that can be loaded as an AMD module or with a simple script tag, or as part of abundle.
  • Request ids correlate JavaScript log messages and server side log messages generated by the same user session.
  • Configure JavaScript loggers in your web.config.
  • Many filtering options to prevent flooding your server with JavaScript log messages.
  • Option to send JavaScript log messages in batches of 2 or more for greater efficiency.
  • Logs JSON objects as well as strings.

Vital Stats

Key concepts

  • Insert loggers in your client side JavaScript, using jsnlog.js (2kb min+gz).
  • Those loggers send your log messages to the JSNLog server side component.
  • This logs the messages in your server side log, using your server side logging package. Supports Log4Net, NLog, Elmah, Common.Logging.

 

(This is how your JSNLog + Elmah interface will look like )

————————————————————————————————-

Now, let’s talk about some installation process and configuration etc 

INSTALLATION

Install JSNLog plus configuration for your logging package

The NuGet packages below install JSNLog itself, plus the configuration needed for it to work with your specific logging package.

  1. Load your solution in Visual Studio, and open the Package Manager Console: Tools | Library Package Manager |Package Manager Console.
  2. Enter the NuGet package at the PM> prompt to install JSNLog plus configuration for your logging package:
Logging Package NuGet package
Log4Net Install-Package JSNLog.Log4Net
NLog Install-Package JSNLog.NLog
Elmah Install-Package JSNLog.Elmah
Serilog Install-Package JSNLog.Serilog
Common.Logging Install-Package JSNLog.CommonLogging

If your logging package is not listed here, install the version for Common.Logging and then install a Common.Loggingadapter for your logging package.

 

STEP – 2

 

Add JSNLog to your pages

Call JSNLog’s Configure method in your pages, before any script tags that load JavaScript that use JSNLog loggers.

  • For Razor (MVC3+), use:
    @Html.Raw(JSNLog.JavascriptLogging.Configure())
    ... your <script> tags

    Your _Layout.cshtml or _Layout.vbhtml would probably be a good place for this.

  • For WebForms, use:
    <%= JSNLog.JavascriptLogging.Configure() %>
    ... your <script> tags

    Your master page would probably be a good place for this.

 

That’s It friends — Now let’s start logging 

function onButton2Click() {
try {
    ...
    // ReferenceError: xyz is not defined
    xyz;
    ...
} catch (e) {
    // Log the exception
    JL().fatalException("something went wrong!", e);
    
    // Rethrow the exception, so the browser 
    // doesn't forget about this error situaion.
    throw e
}

 

You may do some web.config settings change if you may want to – 

 

<configuration> 
    <jsnlog
        enabled="true|false"
        maxMessages="number"
        defaultAjaxUrl="string"
        serverSideLogger="string"
        serverSideLevel="number|TRACE|DEBUG|INFO|WARN|ERROR|FATAL" 
        serverSideMessageFormat="string"
        productionLibraryPath="string" >
    </jsnlog>
</configuration> 

Learning kit – 

Here are the few nice articles which I liked when I was learning this – 

1. obviously their own documentation is more than enough material 

Please refer: http://jsnlog.com/Documentation/GetStartedLogging

2. EVeryone like video tutorials 🙂 

Please refer: http://vimeo.com/channels/jsnlog/videos

Nugets are here too :  https://www.nuget.org/packages/JSNLog.Elmah/

Elmah Resources too : https://code.google.com/p/elmah/

Scott Hanselman’s article on Elmah –                                        http://www.hanselman.com/blog/ELMAHErrorLoggingModulesAndHandlersForASPNETAndMVCToo.aspx

there are many things to cover on these two logger engines like Elmah & jsnLog. Please feel free to send me if you find really nice articles too. 

 

I hope this helps begginers like me… 🙂 Happy coding friends… 

 

 

 

Advertisements

5 thoughts on “Error Logging with Elmah & JSNLog : Javascript exception logger to log exceptions on server side log.

    1. @Abelino, i will have ionic proj very soon and its under my todo list to do the same for ionic proj. I will post again when i will have it.

      Thanks for your freat feedback.

      Like

    2. Also since ionic uses angular , you can use jsnlog for angular and that’s the best way to use anyways.

      You can use jsnlog with any server side logger like elmah or log4net etc.

      Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s