In this lesson, you will learn how to bridge the gap between your application’s logs and its internal health by exposing real-time performance metrics like event loop lag and memory consumption.
While logs capture events (what happened), process telemetry captures state (how the system is feeling). In production, logs might tell you a request failed, but telemetry tells you if that failure was caused by an overloaded event loop or a heap memory exhaustion event.
Measuring Process Health
To gain visibility, you need to monitor the "vitals" of your Node.js process. The two most critical metrics are:
- Memory Usage: Monitored via
process.memoryUsage(), which provides the current Resident Set Size (RSS) and heap usage. - Event Loop Lag: Since Node.js is single-threaded, if the event loop is blocked, your application stops processing tasks. You can measure this by setting a
setIntervalthat records the delay between intended and actual execution time.
Here is a simple pattern to capture these metrics and integrate them into your structured logging stream:
const monitorProcess = () => {
const start = process.hrtime();
setTimeout(() => {
const diff = process.hrtime(start);
const lag = (diff[0] * 1e3 + diff[1] * 1e-6) - 100; // Expected delay
const { rss, heapUsed } = process.memoryUsage();
// Send to your existing logging pipeline
logger.info('process_telemetry', {
eventLoopLag: Math.max(0, lag),
memoryRssBytes: rss,
memoryHeapUsedBytes: heapUsed
});
}, 100);
};
setInterval(monitorProcess, 5000);
Strategic Integration
Don’t treat telemetry as a separate silo. By injecting these metrics into your structured log flow, you gain "contextual snapshots." If you see a spike in log volume or a latency increase, your monitoring tools can correlate that specific request with the state of the event loop at that exact microsecond.
When configuring your observability platform, ensure these fields are indexed so you can trigger alerts when, for example, heapUsed exceeds 80% of your container limit or eventLoopLag consistently drifts above 50ms.
Key Takeaway: Process telemetry transforms your logs from a post-mortem record into a proactive dashboard of your application's operational capacity.