CodeBlanks Logo Icon CodeBlanks

Structured logging

Learn structured logging and JSON format.

Structured logging

Structured logging writes logs in a structured format like JSON instead of plain text. This makes logs easy to search and filter programmatically. It is the standard in production systems.

Example: logger.info({ user: "Ayşe", action: "login" });. Winston prints this as JSON. A plain text log would be a string like user=Ayşe action=login, which is hard to parse. In JSON logs each field is a key; searching by the user field is easy. With Winston's format.json() you can turn all logs into JSON. Structured logs are very valuable in central log systems like ELK (Elasticsearch, Logstash, Kibana). Each log arrives as an object; search and analysis speed up.

winston.format.json()

With Winston's format.json() you can write all logs as JSON. This is the easiest way to do structured logging. The format is applied before transports.

Example: winston.createLogger({ format: winston.format.json(), transports: [new winston.transports.Console()] });. This logger writes each log as JSON. Output: {"level":"info","message":"...","timestamp":"..."}. winston.format.combine() joins multiple formats: winston.format.combine(winston.format.timestamp(), winston.format.json()). This adds a timestamp to the log and writes it as JSON. The format sets the log shape globally; a separate format can also be set per transport.

Practice Create a JSON-formatted logger

Import the winston module. Create a JSON-formatted logger with winston.createLogger({ format: winston.format.json(), transports: [new winston.transports.Console()] }). Write logger.info("Message").

Starter code

index.js
// Import winston
// write here

// Create a JSON-formatted logger
// write here

// Write an info log
// write here

Sample solution

index.js
const winston = require("winston");
const logger = winston.createLogger({
  format: winston.format.json(),
  transports: [new winston.transports.Console()]
});
logger.info("Message");

Expected output

Message

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Why use structured logging?

index.js
logger.info({ user: "Ayşe" })
  • To make logs searchable and filterable Correct answer
  • For faster network
  • To use less disk
  • For more colorful console output

Explanation: Structured logging makes logs searchable.

2 Complete the format.json call

Question
format: winston.format.____(),
Answer
format: winston.format.json(),

Explanation: format.json() uses JSON format.

3 Match each piece to its role

Term Meaning
format.json Writes as JSON
format.timestamp Adds a timestamp
format.combine Combines formats
passing an object Structured logging

All lessons in Advanced