Best Practices for Logging in Node js

|
| By Webner

Collecting Information or data from the system and storing it in a specific file is called logging. It may contain information or data for short or longer periods. Logs are the only way to troubleshoot an issue which the user has with the system.

Do logging correctly:

Creating an app needs debugging and logging by using console.log() or console.error() to display messages to the terminal.

Following are logging levels:

  • Trace – It is an event log file that stores the trace messages during the tracing session. System stores trace messages and generate trace session buffer, then write to the trace log.
  • Debug – There is a set of debug log levels like workflow, validations, and databases that we can reuse using trace flags.
  • Info – It is typically helpful info to log (service start/stop, configuration assumptions, etc). The info needs to invariably have to be obtainable, however, it typically does not care regarding beneath traditional circumstances.
  • Warn – It is something that could probably cause application oddities, but for which automatically recovering is possible. (Such as switching from primary to the backup server, retrying an operation, missing secondary data, etc.)
  • Error – Any error which is fatal to the operation, but not the service or application (can’t open a required file, missing data, etc.). These errors can force user (administrator, or direct user) intervention. These square measures are typically reserved (in my apps) for incorrect association strings, missing services, etc.
  • Fatal – It displays the information regarding the operating system error or loss network connectivity etc.

Best Practices for creating logs

  • Use standard and easily configurable logging framework
  • Use console logs for development only.
  • Analysis of data use custom format and text logs need to custom parsing exact arguments. (use Structured format like JSON or key-value pair)
  • Don’t hard code for vendor libraries
  • Find a way to send the logs from an app that frequently detects the problem.
  • If you know what happened and perhaps should be done, while writing your code, then you can set the alarm for a specific log, instead of firing alerts directly in the code.
  • Security logs are precise. They can use data point when trying to create a baseline for the application for the behavior. Log files contain Debug, Info, Warn Messages and error messages.

There are various Practices by which you can transmit logs

  • First, you must configure a log with limit, if you don’t configure, logs may crash your server
  • Also, check the firewall ports for Syslog, and route traffic to servers with Internet access.
  • Many good agents and libraries offer disk-assisted queues, but one must set them up

Best practices for managing the logs

  • Let end users try out some options instead of making a top-down purchase decision.
  • If end users find any tool hard to use, they will avoid it, offload to experts, or force a switch.
  • Small scale tests are not that meaningful, so send realistic volumes and test the real-world queries.
  • Parsing the logs at search time is slower, and it automatically rules save time over custom ones.

Node js applications generally require logs to store information. Using node js there have inbuilt logging libraries – Winston or Bunyan libraries. These libraries manage logs on relative applications.

Using logging Solution:

  • Track all the data coming to the server from the client-side.
  • It helps to find bugs easily.
  • Track the API’s data.

Bunyan library is a simple and fast JSON logging module. Customer Transports to log data for various locations, such as Slack notification, rotating files, and Syslog daemons.

Example

var bunyan = require('bunyan');
var log = bunyan.createLogger({name: 'papertrail-test'});
log.info('Welcome to the app'); // Just text
log.warn({port: bind}, 'port'); // Text plus metadata

Winston is a library in node.js. Firstly we need to install Winston library in node.js project. It has many log levels.

  • Error
  • Warning
  • Information
  • Debug
  • Custom error level
var winston = require('winston');
winston.level = 'debug';
winston.log('info', 'Book ‘Catch 22’ has been added to the database');

Create Custom logger

var logger = new(winston.Logger)({
  transports: [
    new(winston.transports.Console)({
      timestamp: function() {
        return Date.now();
      },
      formatter: function(options) {
        return options.timestamp() + ' ' + options.level.toUpperCase() +
          ' ' + (options.message ? options.message : '') +
          (options.meta && Object.keys(options.meta).length ? 'nt' +
          JSON.stringify(options.meta) : '');
      }
    })
  ]
});

Save logs in a database

Using Winston library we need to install npm library Winston-mongodb. After installing this library logs can be imported. After that create a new property as a variable in the database.

Configuring Node to send logs to Papertrail

Getting up and running with Papertrail is quick and easy. If you already have log files, you can transmit them to Papertrail using remote_syslog2. This small program will monitor the log files and send new lines to Papertrail.

> remote_syslog -D --tls -p 1234 /var/log/mysqld.log
 
require('winston-papertrail').Papertrail;
var winstonPapertrail = new winston.transports.Papertrail({
  host: 'logs.papertrailapp.com',
  port: 12345
});
 
var logger = new winston.Logger({
  transports: [winstonPapertrail]
});

Leave a Reply

Your email address will not be published. Required fields are marked *