Implementing Logging

1. Using console for Basic Logging

MethodStream
console.log / info / debugstdout
console.warn / errorstderr
new console.Console(stream)Custom output stream

2. Configuring Log Levels

LevelUse
fatalApp about to die
errorOperation failed
warnUnexpected but recoverable
infoLifecycle / business events
debugDiagnostic detail
traceVery 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" })]
});

4. Using pino for High-Performance Logging

Example

import pino from "pino";
const log = pino({ level: "info" });
log.info({ userId: 42 }, "user logged in");
FeatureDetail
Async writespino.transport(...)
Pretty printingpino-pretty in dev
Speed~5x faster than winston

5. Structured Logging

FieldRecommended
timestampISO 8601 / epoch ms
levelString / int
msgHuman message
contextrequestId, userId, traceId
errSerialized 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

SinkTransport
Datadog / NewRelicHTTP agent / sidecar
Loki / ElasticPromtail / Filebeat
SentryError 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)