Monday 16 February 2015

JavaScript Server-Side Logging with JSNlog

Web applications have become increasingly JavaScript-heavy in recent years as we’ve moved to richer and much more responsive web applications. It’s fine debugging JavaScript errors in the browser during development but what about in deployed applications? JSNlog is an open source framework that enables this and can be used in combination with standard .NET logging frameworks such as NLog, log4Net and Elmah. Below I show an example of how to use it with NLog.

Installing NLog

NLog has an installer that’s worth running once, as it supplies some Visual Studio item templates and a code snippet for declaring a logger instance.

private static NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();

But it’s not essential. You can install it via NuGet. You will need to run both of these commands.

Install-Package NLog



Install-Package NLog.Config



The latter adds a config file (NLog.Config). This is where you declare your log files and logging rules.  For example



<targets>
<!--
add your targets here -->
<
target name="logfile" xsi:type="File" fileName="${basedir}/file.txt" />
</targets>
 
<rules>
<!--
add your logging rules here -->
<
logger name="*" minlevel="Info" writeTo="logfile" />
</rules>


Logging a Message From NLog



Suppose we have a ASP.NET MVC application. After setting up the above in the Home controller edit it like this.



using NLog;

namespace WebApplicationNLog2.Controllers
{
public class HomeController : Controller
{
private static Logger logger = LogManager.GetCurrentClassLogger();

public ActionResult Index()
{
logger.Info(
"Sample trace message");
return View();
}
}


 



Then a message is written to the file file.txt in the project folder. It will look something like this.



2015-02-13 12:32:22.5442|INFO|WebApplicationNLog2.Controllers.HomeController|Sample trace message



Installing JSNlog



There is a specific NuGet package to go with the logging framework we happen to be using. So for this example it is:



Install-Package JSNLog.NLog



This installs the dependent package JSNlog among others and also updates the Web.Config as required.



Logging JavaScript



Let’s place some arbitrary JavaScript in the Home controller’s Index view.



First we need to configure JSNlog by placing this line before any script tag that uses JSNlog.



@Html.Raw(JSNLog.JavascriptLogging.Configure())


In a real application we would most likely place this in _Layout.cshtml. Now we can start logging.



<script type="text/javascript">
JL().info("This is a log message");
</script>

Then a message is written to the file file.txt in the project folder. It will look something like this.

2015-02-16 11:27:55.7520|INFO|ClientRoot|This is a log message


All of the logging levels and layout rules that are configurable in frameworks such as NLog and log4net are carried over to the logging of JavaScript in the same way.