How-to: node.js Logger–winston setup / configuration


I am working on node.js based REST API development and I am using this very popular npm middleware called “Winston” for logging errors, exceptions and even info & debug log too.

Why we need it?

Now you must be wondering why we need it since we already have console.log to check logs while development, BUT what happens when we decide to go live? How to access the logs? How to create different log levels?

Well, WINSTON is your answer… following is the setup and configuration.

Manual Logging

If you want to log only specific things that you want to track, there are easy libraries that let you do so. Winston is a very popular one. You can log your output to multiple transports at the same time (e.g: file, console…). It’s also supported by 3rd parties cloud services that will be happy to host those outputs for you (more about that next). 

Here is a simple snippet of how to configure winston and log it to both your console and a file: 

 

var winston = require('winston');

//log your output to a file also

winston.add(winston.transports.File, { filename: 'somefile.log' });

//log some outputs

winston.log('info', 'Hello distributed log files!');

winston.error('Who let the dogs out?!');

How if you want dedicated log files to have all log written to it? which is idle for production anyways –  Here is my setup

– Create folder “helpers” in your project & create “logger.js” in that folder.

– logger.js code

image

– Now in your server.js or app.js (your main node startup file) add this middleware declaration

var logger = require(‘./helpers/logger.js’);

– That’s it…. You are all set…verify by logging any simple information like –

logger.info(‘this is information’);

logger.debug(‘this is debug’);

logger.warn(‘this is warning’);

logger.error(‘this is error’);

Thanks to Winston development team & of course sweet node.js…

Happy Coding Smile

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…