Logging with structured formats helps you save information in a clear, organized way. This makes it easier to find and understand what happened in your app.
0
0
Logging with structured formats in Node.js
Introduction
When you want to track errors and events in your Node.js app clearly.
When you need to send logs to tools that analyze data automatically.
When you want to keep logs readable by both humans and machines.
When you want to include extra details like time, user ID, or request info in logs.
When debugging problems in production or development environments.
Syntax
Node.js
const logger = require('pino')(); logger.info({ key: 'value' }, 'message');
Use a logging library like pino or winston for structured logs.
Logs are usually JSON objects with keys and values for easy parsing.
Examples
This logs an info message with user and action details in JSON format.
Node.js
const pino = require('pino'); const logger = pino(); logger.info({ user: 'alice', action: 'login' }, 'User action');
This logs an error message with error code and message details.
Node.js
const pino = require('pino'); const logger = pino(); logger.error({ errorCode: 500, errorMsg: 'Server error' }, 'Error occurred');
Sample Program
This program logs three messages with structured data: info, warning, and error.
Node.js
const pino = require('pino'); const logger = pino(); logger.info({ event: 'server_start', port: 3000 }, 'Server started'); logger.warn({ memoryUsage: 'high' }, 'Memory usage warning'); logger.error({ error: 'connection_failed', retry: true }, 'Failed to connect');
OutputSuccess
Important Notes
Structured logs are usually in JSON format, which is easy for machines to read.
Use consistent keys in your logs to make searching and filtering easier.
Include timestamps and other context like process ID or hostname for better traceability.
Summary
Structured logging saves data in clear, organized JSON format.
It helps both humans and tools understand logs quickly.
Use libraries like pino in Node.js to create structured logs easily.