0
0
NodejsHow-ToBeginner · 4 min read

How to Implement Logging in Node.js: Simple Guide

In Node.js, you can implement logging using the built-in console methods like console.log for simple output or use libraries like winston for advanced logging features such as log levels, file storage, and formatting. These tools help track app behavior and errors effectively.
📐

Syntax

Node.js provides simple logging with console methods and advanced logging with libraries like winston.

  • console.log(message): Prints a message to the console.
  • winston.createLogger(options): Creates a logger with settings like log levels and output formats.
  • logger.log(level, message): Logs a message at a specified level (e.g., info, error).
javascript
console.log('Hello, world!');

const winston = require('winston');
const logger = winston.createLogger({
  level: 'info',
  format: winston.format.simple(),
  transports: [
    new winston.transports.Console(),
  ],
});

logger.log('info', 'This is an info message');
Output
Hello, world! info: This is an info message
💻

Example

This example shows how to use winston to log messages with different levels and output them to the console and a file.

javascript
import winston from 'winston';

const logger = winston.createLogger({
  level: 'debug',
  format: winston.format.combine(
    winston.format.timestamp({ format: 'YYYY-MM-DD HH:mm:ss' }),
    winston.format.printf(({ timestamp, level, message }) => `${timestamp} [${level}]: ${message}`)
  ),
  transports: [
    new winston.transports.Console(),
    new winston.transports.File({ filename: 'app.log' })
  ],
});

logger.info('App started');
logger.warn('Warning: Low disk space');
logger.error('Error: Unable to connect to database');
Output
2024-06-01 12:00:00 [info]: App started 2024-06-01 12:00:00 [warn]: Warning: Low disk space 2024-06-01 12:00:00 [error]: Error: Unable to connect to database
⚠️

Common Pitfalls

Common mistakes when implementing logging in Node.js include:

  • Using console.log for production logging, which lacks features like log levels and file output.
  • Not handling asynchronous logging properly, which can cause lost logs.
  • Logging sensitive information accidentally.
  • Not rotating log files, leading to large files that are hard to manage.

Always use a logging library like winston or pino for production apps and configure log rotation and levels.

javascript
/* Wrong way: Using console.log only */
console.log('User password: 12345');

/* Right way: Using winston with log levels and no sensitive data */
const winston = require('winston');
const logger = winston.createLogger({
  level: 'info',
  format: winston.format.simple(),
  transports: [new winston.transports.Console()]
});

logger.info('User login attempt');
📊

Quick Reference

Here is a quick summary of logging levels and their typical use:

LevelUse Case
errorCritical problems that need immediate attention
warnWarnings about potential issues
infoGeneral operational messages
debugDetailed debugging information
sillyVery detailed logs, usually for development

Key Takeaways

Use winston or similar libraries for flexible and powerful logging in Node.js.
Avoid using console.log alone for production logging due to lack of features.
Configure log levels and outputs to control what gets logged and where.
Be careful not to log sensitive information like passwords.
Implement log rotation to keep log files manageable.