Logging with node

There are many libraries available for logging in the node ecosystem. The main ones in use are log4js and the winston libraries

Using Log4JS library

The npm module for this library appears here

//requiring the log4js library

var log4js = require('log4js');

//console log is loaded by default, so you won't normally need to do this

//log4js.loadAppender('console');

log4js.loadAppender('file');

//log4js.addAppender(log4js.appenders.console());

log4js.addAppender(log4js.appenders.file('logs/cheese.log'), 'cheese');

var logger = log4js.getLogger('cheese'); //get a refernce to a named instance

//setting the level of information trace, debug, info, warn, error or fatal

logger.setLevel('ERROR');

The library is used heavily in the industry.

It is needed to configure the log4js with the correct appenders and other metadata for the logging framework:

configure('./src/config/log4js-config.json');

const logger = getLogger("app");

Here is an example for log configuration

There are builtin appenders that can be configured for the log4js which can be found here.

Out of the box it supports the following features:

  1. colored console logging
  2. replacement of node's console.log functions (optional)
  3. file appender, with log rolling based on file size
  4. SMTP appender
  5. GELF appender
  6. hook.io appender
  7. Loggly appender
  8. Logstash UDP appender
  9. multiprocess appender (useful when you've got worker processes)
  10. logger for connect/express servers
  11. configurable log message layout/patterns
  12. different log levels for different log categories (make some parts of your app log as DEBUG, others only ERRORS, etc.)

Using Winston library

A multi-transport async logging library for node.js.
Winston is one of the most popular Node.js logging frameworks
First you need to require the module:

  var winston = require('winston');

The default logger is accessible through the winston module directly.

Usage example:

```
var winston = require('winston');

winston.log('info', 'Node. JS logging');
winston.info('this is some important info');

winston.level = 'debug';
winston.log('debug', 'debug messages are logged now');```

results matching ""

    No results matching ""