Log JavaScript client side events in your server side logs
As JavaScript applications grow larger over time, the need for better development practices grow with them. The time that we were just hacking jQuery scripts is long gone. And, since JavaScript based application continue to get a greater share in enterprise applications, we are also in need for better of methods of tracing, logging and debugging bugs.
So, how do we do the most basic of JavaScript logging?
We use the console:
console.log('Something happened !');
You probably use tools like toastr or blackbird (or something else ?) to aid you in your development process. But most of the time, logging doesn't go further than your browser. Information captured in the console is often disregarded once an application moves into production.
Things will break
Make no mistake, one way or the other, your app will break. It might break for one user, or five, or hundreds. It might break today, tomorrow or weeks from now. But, as experience tells us, it will break. And then, when that office phone starts to ring, you realize that all you can really tell your client is that things work fine at your end..
Introducing JsnLog
Jsnlog is a JavaScript logging package that logs JavaScript errors, AJAX timeouts and other client side events in your server side log. It also supports .Net frameworks like Elmah, Log4Net, NLog, Serilog and Common.Logging. Jsnlog is available as standalone, as an AMD module or CommonJS module, or with (MVC.Net) bundles.
Converting a working solution
To start using JsnLog in an existing project you need to go through the following steps:
Install the nuget package.
The different nuget packages can be found here. Just make sure you select the correct package for your server-side logging framework (in my example I used JSNLog.Log4Net).
Update your masterpage
You'll need to call the JSNLog's Configure method in your pages, before any script tags that load JavaScript that use JSNLog loggers. Your master page is probably the best place for this.
@Html.Raw(JSNLog.JavascriptLogging.Configure())
Start Logging
Basically that's it! Use the following code to log to your server:
JL().debug(message); //log a debug message
JL().info(message); //log an info message
JL().error(message); //log an error message
JL().warn(message); //log a warn message
Server side configuration
JsnLog becomes really cool when you look at its configuration features. Take a look at the following things you can do by simply changing your web.config (so without changing any code!):
- Only log messages with a configured severity or higher
- Suppress messages that match a regular expression
- Only log for certain user agents or IP addresses
- Reduce AJAX requests by batching log messages
- Log a session Id
- And many, many more..
Take a look at the documentation here, and take a look at my working demo app here.