How to log in Node.js

Logging provides visibility into application behavior, capturing errors, debugging information, and operational events for troubleshooting and monitoring. As the creator of CoreUI, a widely used open-source UI library, I’ve implemented logging in Node.js applications throughout my 11 years of backend development. The most straightforward approach is using console methods with different log levels for various message types. This method provides immediate logging output without external dependencies, suitable for development and simple applications.

Use console methods with different log levels for structured logging output.

const logger = {
  info: (message, meta = {}) => {
    console.log(JSON.stringify({
      level: 'info',
      message,
      timestamp: new Date().toISOString(),
      ...meta
    }))
  },

  error: (message, error = {}, meta = {}) => {
    console.error(JSON.stringify({
      level: 'error',
      message,
      timestamp: new Date().toISOString(),
      error: {
        message: error.message,
        stack: error.stack
      },
      ...meta
    }))
  },

  warn: (message, meta = {}) => {
    console.warn(JSON.stringify({
      level: 'warn',
      message,
      timestamp: new Date().toISOString(),
      ...meta
    }))
  },

  debug: (message, meta = {}) => {
    if (process.env.NODE_ENV === 'development') {
      console.debug(JSON.stringify({
        level: 'debug',
        message,
        timestamp: new Date().toISOString(),
        ...meta
      }))
    }
  }
}

logger.info('Server started', { port: 3000 })
logger.error('Database connection failed', new Error('Connection timeout'), { database: 'users' })
logger.warn('High memory usage detected', { usage: '85%' })
logger.debug('Processing request', { method: 'GET', path: '/api/users' })

Here the logger object provides methods for different log levels: info, error, warn, and debug. Each method creates a structured JSON log entry with timestamp, level, and metadata. The error method captures both error message and stack trace for debugging. The debug method only logs in development environment to reduce production noise. JSON formatting enables easy parsing by log aggregation tools.

Best Practice Note:

This is the basic logging approach we use in CoreUI Node.js utilities for simple logging needs without external dependencies. Use environment variables to control log levels in production, rotate log files to prevent disk space issues, and consider structured logging libraries like Winston or Pino for production applications requiring advanced features.


Speed up your responsive apps and websites with fully-featured, ready-to-use open-source admin panel templates—free to use and built for efficiency.


About the Author