Node.js
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.
Exercise 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").
Show example solution
const winston = require("winston");
const logger = winston.createLogger({
format: winston.format.json(),
transports: [new winston.transports.Console()]
});
logger.info("Message");
Test yourself
-
Why use structured logging?
logger.info({ user: "Ayşe" })
- To make logs searchable and filterable
- For faster network
- To use less disk
- For more colorful console output
Show answer
To make logs searchable and filterable — Structured logging makes logs searchable.
-
Complete the format.json call
format: winston.format.____(),
Show answer
format: winston.format.json(),
-
Match each piece to its role
- format.json
- Writes as JSON
- format.timestamp
- Adds a timestamp
- format.combine
- Combines formats
- passing an object
- Structured logging
Next lesson: Pino