Arrange Act Assert

Jag Reehals thinking on things, mostly product development

Structured logging with Pino

14 Nov 2023

Structured logging focuses on capturing data in a consistent and machine-readable format.

Unlike traditional text-based logs, structured logs are more straightforward to query and analyse, making extracting insights and debugging issues simpler.

Engineering coding

In this post, we'll take a look at an example of how structured logging with Pino.

In the examples below the logging approach is unstructured and lacks context, making it hard to parse or search through logs.

import pino from 'pino';

const logger = pino();

logger.info('User logged in', userId, new Date());
logger.info(`User: ${userId} logged in at: ${new Date()}`);

Instead you should switch to structured logging like this:

import pino from 'pino';

const logger = pino();

logger.info(
  {
    userId,
    date: new Date(),
  },
  'User logged in'
);

This output is structured in JSON format, making parsing and analyzing programmatically more accessible.

Adopting Pino for structured logging in Node.js applications significantly improves log management. It ensures logs are human-readable and machine-friendly, enhancing debugging and monitoring.

Node.js logging