websockets-logger
v0.3.1
Published
Lightweight WebSocket logger that forwards console output to a centralized hub.
Readme
websockets-logger
A tiny TypeScript-first helper that forwards your application logs to a Cloudflare Durable Object hub and lets you inspect everything through the console-omattic-com UI. Drop it into any browser or Node.js project, keep your existing console.* calls, and get a centralized stream of JSON-friendly log events.
Quick start
Install the package inside your app (once this workspace is published you can reference it via a local path or private registry):
pnpm add websockets-loggerInitialize the logger as early as possible in your app:
import { initializeWebSocketLogger, wsLog } from 'websockets-logger';
initializeWebSocketLogger({
wsUrl: 'wss://websockets.omattic.com/hub',
source: 'my-app', // optional – defaults to host/pid + random suffix
apiKey: 'your-api-key', // optional – for authenticated hubs
});
wsLog.info('Hello central console');If you prefer to keep using console.*, flip on the auto-patching helper:
initializeWebSocketLogger({
wsUrl: 'wss://websockets.omattic.com/hub',
source: 'marketing-site',
apiKey: 'your-api-key', // optional – for authenticated hubs
patchConsole: true,
});With patchConsole: true the module swaps the global console methods so every call goes through the logger and optionally prints locally. By default local printing is disabled to avoid double output; enable it by passing consolePassthrough: true or enableConsole: true.
Options
| Option | Default | Notes |
| --- | --- | --- |
| wsUrl | – | Required WebSocket endpoint, e.g. wss://websockets.omattic.com/hub from websockets-omattic-com. |
| source | hostname / pid + random | Acts as the clientId inside the Durable Object. Show up in the console UI as the emitter. |
| topic | logs | Broadcast topic used when sending messages. Leave as-is to interoperate with the console worker and UI. |
| subscriptionTopic | source | Initial subscription topic sent on connection. Normally you should not change this. |
| enableConsole | true (or false when patchConsole is set) | Mirror messages to the original console methods that were present during initialization. |
| bufferMessages | true | Queue log entry objects while the socket reconnects. |
| maxBufferSize | 100 | Upper bound for the in-memory buffer. Oldest messages are dropped first. |
| reconnectInterval | 5000 ms | Automatic reconnect cadence. Set to 0 to disable. |
| onConnectionChange | – | (state) => void callback with connecting, connected, or disconnected. Useful for status indicators. |
| onMessage | – | Receive raw messages coming from the hub (handy if you extend the DO to push commands). |
| webSocketFactory | globalThis.WebSocket | Supply your own implementation when running outside the browser, e.g. () => new (require('ws'))(url). |
| initialContext | {} | Key/value payload merged into every log message. Update at runtime via logger.updateContext(). |
| apiKey | – | Optional API key for authentication. Automatically included in the subscription message payload. Works in both browser and Node.js environments. |
| patchConsole | false | Only on initializeWebSocketLogger. Auto routes console calls through the logger. |
| consoleLevels | all | Restrict which console methods are patched. |
| consolePassthrough | mirrors enableConsole | When patching console, forward the call to the original console after logging. |
Runtime helpers
import {
WebSocketLogger,
initializeWebSocketLogger,
getWebSocketLogger,
patchConsole,
unpatchConsole,
wsLog,
} from 'websockets-logger';WebSocketLogger– instantiate manually if you need multiple isolated loggers.initializeWebSocketLogger– creates a singleton, optionally patches the global console, and returns the instance.getWebSocketLogger– retrieve the singleton ornull.patchConsole/unpatchConsole– control console interception explicitly.wsLog– drop-in replacement object withlog/error/warn/info/debugplussetRequestId,setContext,updateContext,clearContext.
Request-scoped metadata
const logger = initializeWebSocketLogger({ wsUrl: HUB_URL });
logger.setRequestId('abc-123');
logger.updateContext({ userId: 'uid_42', featureFlag: 'beta-dashboard' });
logger.info('User opened dashboard');
logger.clearContext(['featureFlag']);
logger.clearRequestId();Every payload delivered to the hub includes the timestamp, level, source, optional request id, and context blob. The console-omattic-com UI already highlights requestId and prettifies JSON content; adding more context lets you extend that view without changing the worker.
Using inside Node.js
Pass your own WebSocket implementation and patch the console:
import WebSocket from 'ws';
import { initializeWebSocketLogger } from 'websockets-logger';
initializeWebSocketLogger({
wsUrl: 'wss://websockets.omattic.com/hub',
source: `worker-${process.pid}`,
apiKey: 'your-api-key', // optional – for authenticated hubs
webSocketFactory: (url) => new WebSocket(url),
patchConsole: true,
enableConsole: true, // still prints locally
});Relationship to the hub and console projects
- websockets-omattic-com hosts the Cloudflare Worker + Durable Object hub that relays messages between clients. This logger automatically subscribes using its
sourceasclientIdand publishes log entries to the sharedlogstopic. - console-omattic-com is the React UI that subscribes to the
alltopic and renders incoming log events. If you follow the defaults, every log produced through this module appears there instantly with request id and JSON detection.
Development
pnpm install
pnpm buildThe build pipeline uses tsup to emit dual ESM/CommonJS bundles plus declaration files into dist/. To start iterating locally you can pnpm link --global and consume the package in another repo via pnpm link --global websockets-logger.
Continuous publishing
- GitHub Actions workflow:
.github/workflows/publish.yml. - Trigger: every push to
mainafter lint/build. - Publishes with
pnpm publish --access publicwhen thepackage.jsonversion is not already on npm. - Requires an
NPM_TOKENrepository secret with publish rights to thewebsockets-loggerpackage.
