DEV Community

Cover image for logging in Node.js
OLUKINNI
OLUKINNI

Posted on

logging in Node.js

Logging can be described as the process of writing information in a log file, which can be used later for debugging in the case of any issue. Logging is an essential part of understanding the complete application life cycle of the Node.js program. From starting to debugging and adding new features, logs provide support by analyzing the data, and we can resolve bugs much easier and quicker by detecting errors as soon as they occur. There are common levels of logging in Node.js: error, warn, info, debug. In this article, we will be discussing about how logging could be us to debug easily and it advantages.

The following are ways to log in Node.js:

console.log

The original method of logging is console.log which is a function that writes a message to log on the debugging console, but you have little control over it. When running console.log, you may notice a negligible decrease in performance. To avoid negatively impacting performance, I recommend switching to a logging library when your project begins to expand.

console.log(level, message)
Enter fullscreen mode Exit fullscreen mode

Use of log library

Logging libraries help developers create and manage log events, which can increase the overall efficiency and functionality of your application. Some of the most popular logging libraries for Node are Winston, Pino, Bunyan, and Morgan.

Winston

Winston includes storage options, different log levels & queries, and a profiler. Winston might be the best choice because it supports multiple transports.

const winston = require('winston');
const config = require('./config');

const enumerateErrorFormat = winston.format((info) => {
  if (info instanceof Error) {
    Object.assign(info, { message: info.stack });
  }
  return info;
});

const logger = winston.createLogger({
  level: config.env === 'development' ? 'debug' : 'info',
  format: winston.format.combine(
    enumerateErrorFormat(),
    config.env === 'development' ? winston.format.colorize() : winston.format.uncolorize(),
    winston.format.splat(),
    winston.format.printf(({ level, message }) => `${level}: ${message}`)
  ),
  transports: [
    new winston.transports.Console({
      stderrLevels: ['error'],
    }),
  ],
});

module.exports = logger;
Enter fullscreen mode Exit fullscreen mode

Pino

This logging library is very popular for its low overhead and minimalism. It uses less resources for logging by using a worker thread for processing.

const pino = require('pino');

// Create a logging instance
const logger = pino({
level: process.env.NODE_ENV === 'production' ? 'info' : 'debug',
});


logger.info('Application started!');
Enter fullscreen mode Exit fullscreen mode

Bunyan

Bunyan is another fast JSON logging library that supports multiple transports and uses a CLI for filtering the logs. It has a refined method that produces what they should do. My favorite feature about Bunyan is the log snooping, which helps in debugging failures in production.

const bunyan = require('bunyan');
const log = bunyan.createLogger({name: 'myapp'});
log.info('My App');


{"name":"myapp","hostname":"banana.local","pid":40161,"level":30,"msg":"My App","time":"2022-04-04T18:24:23.851Z","v":0}
Enter fullscreen mode Exit fullscreen mode

Other cool features of Bunyan are a stream system for controlling where logs are located, support for environments aside from Node.js, and that JSON objects are serialized by default.

Morgan

Logging requests in nodejs can as well be accomplished with a tool called morgan, which gets the server logs and systematizes them to make them more readable.

To use Morgan, simply set the format string:

const morgan = require('morgan');
app.use(morgan('dev'));
Enter fullscreen mode Exit fullscreen mode

Log management system

Depending on how big your application is, it may be helpful to pull the logs out of your application and manage them separately using a log management system.
Log management systems allow you to track and analyze logs as they happen in real-time, which in turn can help improve your code. A log management system can help you keep track of useful data including backend errors, anomalies, log sources, and production errors.
For log analysis and log management tools, I recommend Sentry, Loggly, McAfee Enterprise, Graylog, Splunk, Logmatic or Logstash.

Health monitoring tools

Health monitoring tools are a good way to keep track of your server performance and identify causes of application crashes or downtime. Most health monitoring tools offer error tracking as well as alerts and general performance monitoring. Some developers find error tracking particularly frustrating in Node.js, so using a health monitoring tool can help alleviate some of those difficulties.

Below are few popular monitoring tools for Node.js:

Conclusion

For an optimal logging and monitoring experience in Node.js, might be best to choose the library that suits your needs. It would also be great if you follow some logging best practices to reap the most benefits as they are software engineers’ best friend. Do not log important information like the credit card details of the user and be careful of what you log.
Try to log everything which you feel could be used later. Obviously, you will figure these things out when it is faced, but try to start with the bare minimum.

Thank you.🙂👍

Top comments (4)

Collapse
 
frezyx profile image
Stanislav Ilin

Cool article.
Setting up the right logging environment is very important!

Collapse
 
olukinni029 profile image
OLUKINNI

Thank you.

Collapse
 
webjose profile image
José Pablo Ramírez Vargas

Why no mention of structured logging? That's like a must nowadays. To contribute, I'll mention structured-log. It is my logger of choice, especially because it is inspired in Serilog, my preferred .Net structured logger. Cheers.

Collapse
 
olukinni029 profile image
OLUKINNI

Thank you for the contribution,will check that as well.