Monitoring and Logging

1. Implementing Structured Logging

LibraryLang
pinoNode (fast JSON)
winstonNode (flexible)
zapGo
logbackJava
structlogPython

Example: pino structured

import pino from "pino";
const log = pino({ level: process.env.LOG_LEVEL ?? "info" });
log.info({ event:"ws_open", userId, ip, ua, sockId }, "connection opened");

2. Logging Connection Events

EventFields
ws_opensockId, userId, ip, ua, ts
ws_closesockId, code, reason, duration, wasClean
ws_errorsockId, err message
ws_auth_ok / failsockId, userId, reason

3. Logging Message Events

Warning: Never log raw message payloads at info level — PII risk. Log size, type, and id only.
FieldDetail
typeMessage type
idCorrelation
sizeBytes
dirin / out
latency_msFor RPCs

4. Tracking Connection Metrics

MetricType
ws_connections_activeGauge
ws_connections_opened_totalCounter
ws_connections_closed_totalCounter (by code)
ws_connection_duration_secondsHistogram

5. Monitoring Message Throughput

MetricDetail
msgs_sent_total / secOutbound rate
msgs_received_total / secInbound rate
bytes_sent / receivedBandwidth
buffer_high_watermarkBackpressure signal

6. Tracking Error Rates

MetricTag By
parse_errors_totalschema
auth_errors_totalreason
rate_limited_totaltier
abnormal_close_totalcode

7. Using Application Performance Monitoring

ToolStrength
Datadog APMDistributed traces + logs
New RelicFull-stack
SentryError tracking + traces
OpenTelemetryVendor-neutral

8. Implementing Custom Metrics

Example: prom-client

import client from "prom-client";
const active = new client.Gauge({ name:"ws_connections_active", help:"" });
wss.on("connection", (ws) => {
  active.inc();
  ws.on("close", () => active.dec());
});

9. Setting Up Alerts

AlertTrigger
Connection drop spikeclose_rate > 3× baseline
Memory near capRSS > 85%
Auth failure surgeauth_errors / sec spike
Pub/sub lagEnd-to-end > 1s

10. Analyzing Logs

ToolDetail
Loki + GrafanaLightweight, label-based
ELKElasticsearch + Kibana
SplunkEnterprise
Datadog LogsUnified with metrics/traces