Mikael Balin

Logging Objects in Node.js: Understanding util.inspect

Jan 29, 2025

2 min read

Node.js

Logging is an essential part of debugging and monitoring applications. In Node.js, console.log() is commonly used for logging, but when dealing with complex objects, it has limitations. This is where util.inspect() comes in, providing a more detailed and configurable way to inspect objects.

Why console.log() Isn't Always Enough #

console.log(obj) works well for simple objects, but it has drawbacks:

  • It doesn't provide depth control for deeply nested objects.
  • Circular references can cause issues.
  • It may not display non-enumerable properties or custom object representations.

Example:

const obj = { a: 1, b: { c: { d: { e: 2 } } } };
console.log(obj);

Output:

{ a: 1, b: { c: { d: [Object] } } }

Notice how the nested structure is truncated with [Object].

Introducing util.inspect #

The util.inspect() function from Node.js's built-in util module is designed for logging and debugging complex objects. It provides more control over object depth, formatting, and colorization.

Basic Usage #

const util = require('util');
const obj = { a: 1, b: { c: { d: { e: 2 } } } } };
console.log(util.inspect(obj));

Output:

{ a: 1, b: { c: { d: { e: 2 } } } } }

Unlike console.log(), util.inspect() does not truncate deep objects unless configured otherwise.

Customizing Output #

1. Controlling Depth #

By default, util.inspect() limits depth to 2 levels. Use the depth option to inspect deeper objects:

console.log(util.inspect(obj, { depth: null }));

Setting depth: null ensures all levels are displayed.

2. Colorizing Output #

Enable colored output for better readability:

console.log(util.inspect(obj, { colors: true }));

3. Showing Non-Enumerable Properties #

By default, non-enumerable properties are hidden. To show them:

console.log(util.inspect(obj, { showHidden: true }));

Alternative: console.dir() #

For logging objects, console.dir() offers similar functionality:

console.dir(obj, { depth: null, colors: true });

It’s a simpler alternative when you only need structured object output.

Using a Logger (winston, pino) #

For production applications, structured logging with loggers like Winston or Pino is recommended.

Example using Pino:

const pino = require('pino');
const logger = pino({ prettyPrint: true });
logger.info(obj);

Conclusion #

util.inspect() is a powerful tool for debugging complex objects in Node.js, offering more control over depth, colors, and hidden properties. While console.log() works for basic cases, util.inspect() is essential for deep object inspection, especially when dealing with circular references or non-enumerable properties.

Next time you're logging in Node.js, consider using util.inspect() for better clarity and control! 🚀

Share this article