Documentation Menu

Installation

Working sample code

Logging server side

  1. Install jsnlog.js from NPM:
    npm install jsnlog
  2. Load jsnlog into your code (alternatives):
    var JL = require('jsnlog').JL;
  3. By default, jsnlog.js logs to the console. To make it easy to log to a database or a logging service, you can use Winston transports as well (see how).

If you will only be logging from a Node.js program, that's the installation done. Head on to the Getting Started page.

If you have a web site, you'll want to log exceptions and other interesting events in the client and store the log messages on the server. Continue on.

Logging client side

Two things need to be done:

  • Load jsnlog.js on the client. This will send log messages via AJAX to the server.
  • Receive the log messages on the server and log them server side.

Load jsnlog.js on the client

You have these options to load jsnlog.js on the client:

  1. With a simple script tag. If necessary, copy jsnlog.js from the node_modules/jsnlog directory to the directory where you keep your client side JavaScript files.
  2. As an AMD module (how).
  3. As part of a combined JavaScript file generated by Browserify (how).

Note that the same jsnlog.min.js file happily works on both the client and server. On the client, by default it automatically sends log messages via AJAX to the server. On the server, by default it sends log messages to the console.

Receive and store log messages on the server

The jsnlog.js running on the client by default sends log messages to:

/jsnlog.logger

(how to change)

These log messages are POSTs, and the log messages sit in the body as a JSON object. You will want to receive those messages on the server, and pass them on to the server side jsnlog.js, for server side logging.

To make this easier, the jsnlog-nodejs package exposes a function that takes the JSON object and logs all the messages:

npm install jsnlog-nodejs
var JL = require('jsnlog').JL;
var jsnlog_nodejs = require('jsnlog-nodejs').jsnlog_nodejs;
// Read JSON object from message body var jsonBody = ....;
// Pass the log messages to the server side jsnlog.js jsnlog_nodejs(JL, jsonBody);

For example, if you use Express, you could add a route to receive the log messages:

npm install express
npm install body-parser
var express = require('express');
var bodyParser = require('body-parser'); 
var app = express();
// Ensure that the JSON objects received from the client get parsed correctly. app.use(bodyParser.json())
// jsnlog.js on the client by default sends log messages to /jsnlog.logger, using POST. app.post('*.logger', function (req, res) { jsnlog_nodejs(JL, req.body);
// Send empty response. This is ok, because client side jsnlog does not use response from server. res.send(''); });

Now that the installation is done, visit the Getting Started page.