What is Logging?
It helps developers identify and diagnose issues or bugs in their code by providing a detailed record of what happened during program execution. By analyzing log messages, developers can trace the flow of execution, pinpoint the source of errors, and understand the sequence of events leading up to a problem. Logging typically involves the generation of log messages, which consist of text-based records containing relevant information about an event or activity. These messages are then written to log files or sent to a centralized logging system for storage and further analysis. Log messages often include timestamps, severity levels, contextual information, and details specific to the event being logged.
We can use the following node library to implement the logs in the javascript application:
1: Winston:
Winston is the logging library, which support multiple transport. Transport is the storage for logs. We can also configure different logging level. Winston supports log formatting.
Installation
npm install winston
Usage
The recommended way to use winston
is to create your own logger. The simplest way to do this is using winston.createLogger
:
const winston = require('winston'); const logger = winston.createLogger({ level: 'info', format: winston.format.json(), defaultMeta: { service: 'user-service' }, transports: [ // // - Write all logs with importance level of `error` or less to `error.log` // - Write all logs with importance level of `info` or less to `combined.log` // new winston.transports.File({ filename: 'error.log', level: 'error' }), new winston.transports.File({ filename: 'combined.log' }), ], }); // // If we're not in production then log to the `console` with the format: // `${info.level}: ${info.message} JSON.stringify({ ...rest }) ` // if (process.env.NODE_ENV !== 'production') { logger.add(new winston.transports.Console({ format: winston.format.simple(), })); }
More detail: https://www.npmjs.com/package/winston
2: Loglevel
Minimal lightweight simple logging for JavaScript. loglevel replaces console.log() and friends with level-based logging and filtering, with none of console’s downsides.
Installation
npm install loglevel
var log = require('loglevel'); log.warn("unreasonably simple");
More detail: https://www.npmjs.com/package/loglevel
3: Npmlog
This logger is very basic. It does the logging for npm. It supports custom levels and colored output.
Installation
npm install npmlog --save
Usage
var log = require('npmlog') log.info('fyi', 'I have a kitty cat: %j', myKittyCat)var log = require('npmlog')
More detail: https://www.npmjs.com/package/npmlog