Implementing Logging
1. Using console for Basic Logging
| Method | Stream |
console.log / info / debug | stdout |
console.warn / error | stderr |
new console.Console(stream) | Custom output stream |
2. Configuring Log Levels
| Level | Use |
| fatal | App about to die |
| error | Operation failed |
| warn | Unexpected but recoverable |
| info | Lifecycle / business events |
| debug | Diagnostic detail |
| trace | Very verbose |
3. Using winston for Advanced Logging
Example
import winston from "winston";
const logger = winston.createLogger({
level: "info",
format: winston.format.json(),
transports: [new winston.transports.Console(), new winston.transports.File({ filename: "app.log" })]
});
Example
import pino from "pino";
const log = pino({ level: "info" });
log.info({ userId: 42 }, "user logged in");
| Feature | Detail |
| Async writes | pino.transport(...) |
| Pretty printing | pino-pretty in dev |
| Speed | ~5x faster than winston |
5. Structured Logging
| Field | Recommended |
| timestamp | ISO 8601 / epoch ms |
| level | String / int |
| msg | Human message |
| context | requestId, userId, traceId |
| err | Serialized stack + code |
6. Writing Logs to Files
Note: Prefer logging to stdout and let the orchestrator (PM2, Docker, journald) handle file routing — 12-Factor App.
7. Using Log Rotation (rotating-file-stream)
Example
import { createStream } from "rotating-file-stream";
const stream = createStream("app.log", { interval: "1d", compress: "gzip", maxFiles: 14 });
8. Adding Context to Logs
Example: Per-request context
import { AsyncLocalStorage } from "node:async_hooks";
const als = new AsyncLocalStorage();
app.use((req, _res, next) => als.run({ requestId: req.id }, next));
const ctx = () => als.getStore() ?? {};
log.info({ ...ctx(), event: "x" });
9. Sending Logs to External Services
| Sink | Transport |
| Datadog / NewRelic | HTTP agent / sidecar |
| Loki / Elastic | Promtail / Filebeat |
| Sentry | Error tracking SDK |
| Cloud (CloudWatch / Stackdriver) | Native runtime integration |
10. Implementing Log Aggregation
Aggregation Pipeline
app (stdout JSON)
↓
shipper (Filebeat / Vector / Fluent Bit)
↓
buffer (Kafka / Redis / Loki)
↓
storage + search (Elasticsearch / OpenSearch)
↓
UI (Kibana / Grafana)