Drop-in observability for Node.js services — distributed tracing, runtime metrics, continuous profiling, structured logging, and stage monitoring in a single package.
- Distributed Tracing — Auto OpenTelemetry instrumentation for HTTP, Fastify, AMQP, AWS SDK, MongoDB, Redis, and Pino.
- Runtime + Host Metrics — CPU, memory, GC, and event-loop metrics exported every 5 s over OTLP gRPC.
- Continuous Profiling — Optional Pyroscope integration with automatic
trace_id/span_id/profile_idlabels. - Structured Logging — Pino-based
Loggerwith ISO timestamps,errserializer, and auto-injected trace IDs. - Stage Monitoring —
createZMonitorfor lifecycle logs with monotonic-clock durations. - Fastify Plugin — Request/response logging plugin with sampling-aware behavior and an HTTP-aware
HttpErrorclass.
npm install @ztube/observability
# or
pnpm add @ztube/observability
# or
yarn add @ztube/observability- Node.js >= 22. Enforced at install (a
preinstallcheck fails fast) and again at boot — older runtimes get a clear error, never a silent runtime bug. - TypeScript >= 5.0 (for typed consumers).
- Both ESM and CommonJS are supported —
importandrequireboth resolve. - Fastify is an optional peer. Only install
fastify@^5if you use@ztube/observability/fastify; the root export needs nothing extra.
Important
initTelemetry must run before any module you want instrumented. Put it at the very top of your application entry file.
// src/init.ts — imported first in your entrypoint
import { initTelemetry } from "@ztube/observability";
initTelemetry({
serviceName: "video-processor",
serviceVersion: "2.4.0",
otelEndpoint: "http://otel-collector:4317",
pyroscopeServerAddress: "http://pyroscope:4040", // optional
logLevel: "info",
samplingRatio: 0.1,
});// src/index.ts
import "./init.js";
import { addCustomSpan, Logger } from "@ztube/observability";
await addCustomSpan("process-frame", async (span) => {
span.setAttribute("frame.id", frameId);
Logger.logInfo("processing", { frameId });
return processFrame(frameId);
});The same API is available via require for CommonJS / older TypeScript projects:
// init.cjs — required first in your entrypoint
const { initTelemetry } = require("@ztube/observability");
initTelemetry({
serviceName: "video-processor",
serviceVersion: "2.4.0",
otelEndpoint: "http://otel-collector:4317",
});
// the Fastify plugin too
const { fastifyLoggingPlugin } = require("@ztube/observability/fastify");| Subpath | Purpose |
|---|---|
@ztube/observability |
Telemetry init, tracing helpers, Logger, createZMonitor |
@ztube/observability/fastify |
fastifyLoggingPlugin, HttpError, route-level log config types |
Wrap business logic in custom spans. Spans are automatically linked to Pyroscope profiles when profiling is enabled.
import { addCustomSpan, isSampled } from "@ztube/observability";
const data = await addCustomSpan("process-frame", async (span) => {
span.setAttribute("frame.id", frameId);
// gate expensive attribute/log work behind the sampler
if (isSampled()) {
span.setAttribute("frame.debug", JSON.stringify(debugInfo));
}
return processFrame(frameId);
});Exceptions thrown inside the callback are recorded on the span (recordException + SpanStatusCode.ERROR) and re-thrown.
For non-Fastify HTTP servers, attach pyroscopeMiddleware to propagate profile labels per request:
import { pyroscopeMiddleware } from "@ztube/observability";
expressApp.use(pyroscopeMiddleware);The Fastify plugin registers it for you when enableProfiling: true.
Logger is the package-wide Pino-backed singleton. initTelemetry reconfigures it with your serviceName and logLevel.
import { Logger } from "@ztube/observability";
Logger.logInfo("Operation started", { userId: "123" });
Logger.logWarning("Resource limit nearing", { limit: 80 });
try {
// ...
} catch (error) {
Logger.logError("Failed to process request", error, { flowId: "abc" });
}Logger implements LoggerPort (the public interface; LoggerManager is type-only). Spawn request- or job-scoped child loggers with bound metadata:
import { Logger, type LoggerPort } from "@ztube/observability";
const childLogger: LoggerPort = Logger.createChild({ traceId: "xyz-789" });
childLogger.logInfo("Processing chunk");For DI containers, depend on LoggerPort and inject Logger (or a createChild of it) at the composition root.
createZMonitor instruments discrete steps of a pipeline or background job with lifecycle logs and monotonic-clock duration.
import { createZMonitor } from "@ztube/observability";
const monitor = createZMonitor({
processName: "render-job",
stageName: "encode",
businessId: jobId,
});
monitor.logStarted();
try {
const out = await encode();
monitor.logSuccess(out);
} catch (err) {
monitor.logAborting(err as Error);
}Every log line includes processName, stageName, businessId, status, and durationMs (computed from process.hrtime.bigint() since logStarted()). Available lifecycle calls: logStarted, logSuccess, logRetry, logAborting, logInvalidInput.
Enable structured request/response logging on your Fastify service.
import { fastifyLoggingPlugin } from "@ztube/observability/fastify";
server.register(fastifyLoggingPlugin, {
enableByDefault: true,
logStarted: false,
logSuccess: true,
enableProfiling: true,
});| Option | Type | Default | Description |
|---|---|---|---|
enableByDefault |
boolean |
false |
Log HTTP for every route unless routeOptions.config.logHttp === false. |
logStarted |
boolean |
false |
Emit a log line when a request starts. |
logSuccess |
boolean |
true |
Emit a log line on successful response. |
enableProfiling |
boolean |
false |
Register pyroscopeMiddleware as an onRequest hook. |
Attach RouteLogConfig to routeOptions.config to override the global defaults for a single route.
import type { RouteLogConfig } from "@ztube/observability/fastify";
server.get("/health", {
config: {
logHttp: false,
message: "health-check",
} satisfies RouteLogConfig,
}, healthHandler);| Field | Type | Purpose |
|---|---|---|
logHttp? |
boolean |
Override enableByDefault. |
logStarted? |
boolean |
Override global logStarted. |
logSuccess? |
boolean |
Override global logSuccess. |
selectFields? |
(ctx: LogSelectingContext) => Record<string, unknown> |
Pick extra fields per LOG_PHASE (STARTED / SUCCESS / ERROR). |
message |
string |
Log message; falls back to the handler's function name + phase. |
HttpError lives in @ztube/observability/fastify so the plugin's onError hook can recognize the shape without a circular import.
import { HttpError } from "@ztube/observability/fastify";
throw new HttpError({
statusCode: 503,
message: "render queue unavailable",
expose: true,
cause: brokerErr,
details: { attempts: 3 },
});Warning
HttpError is HTTP-only. Don't throw it from AMQP consumers, workers, or background jobs — statusCode is meaningless there. Use plain Error subclasses for non-HTTP failure paths and translate to HttpError at the controller boundary.
expose default. When omitted, it is derived from statusCode: true for 4xx, false for 5xx. So 5xx bodies never leak internal messages unless you opt in.
Log shape. When a route throws HttpError, the log line carries err.statusCode, err.expose, err.details, and err.cause under the err.* namespace via Pino's stdSerializers.err. The onError hook duck-types on statusCode, so Fastify-native validation errors (FastifyError) also log the correct status.
Response shape. Your app's setErrorHandler decides the wire format. A typical handler:
server.setErrorHandler((err, _req, reply) => {
const statusCode = (err as HttpError).statusCode ?? 500;
const expose = (err as HttpError).expose ?? statusCode < 500;
reply.status(statusCode).send({
error: expose ? err.message : "Internal error",
});
});details is intentionally log-only and never serialized to the response.
| Option | Type | Default | Description |
|---|---|---|---|
serviceName |
string |
required | Service identifier (service.name resource attribute). |
serviceVersion |
string |
required | Semantic version (service.version resource attribute). |
otelEndpoint |
string |
required | OTLP gRPC endpoint for traces + metrics (e.g. http://otel-collector:4317). |
pyroscopeServerAddress |
string |
undefined |
Pyroscope address; if omitted, profiling stays disabled. |
logLevel |
string |
process.env.LOG_LEVEL ⇒ "info" |
Pino log level. |
samplingRatio |
number |
1.0 |
Trace sampling probability (0–1) via TraceIdRatioBasedSampler. |
| Option | Type | Default | Description |
|---|---|---|---|
serviceName |
string |
undefined |
Pino base.serviceName field. |
level |
string |
process.env.LOG_LEVEL ⇒ "info" |
Pino log level. |
customDestination |
pino.DestinationStream |
pino.destination(1) (stdout) |
Custom destination — useful in tests. |
Tip
When LOG_LEVEL is set in the environment, both Logger and createZMonitor pick it up automatically.
Two rules drive every observability decision in this package:
- Errors always log.
fastifyLoggingPlugin.onErrorandZMonitor.logAborting/logInvalidInputignore the sampler. - Non-error logs respect the sampler.
fastifyLoggingPlugin.onRequest/onSendandZMonitor.logStarted/logSuccess/logRetryshort-circuit whenisSampled()isfalse— i.e. when the trace was dropped bysamplingRatio. With no active span,isSampled()returnstrueso local dev still logs everything.
This keeps the hot path quiet under heavy sampling while guaranteeing failure visibility.
Runnable examples ship in src/example/:
monitor-example/—createZMonitorlifecycle demo.otel/fastify/— full Fastify service with tracing, metrics, profiling, and structured logs.otel/express/— Express counterpart that demonstrates framework portability.
Run the Fastify example end-to-end (runs the TS source directly via tsx — no build step):
pnpm example:fastifypnpm build # tsup — dual ESM + CJS + .d.ts into dist/
pnpm test # vitest run
pnpm type-check # tsc -p tsconfig.json --noEmit
pnpm lint # biome check . --writeThis entire section applies only to the closed-network system. Public-npm consumers install from the registry (see Installation) and never build or publish this package themselves. New versions must be uploaded to the closed-network registry from inside the closed system.
To ship a version into the closed-network registry, build a tarball and upload it by hand from within the closed system:
pnpm install # deps (fresh clone)
pnpm release # changeset — prompts bump type + note, bumps package.json + CHANGELOG.md
pnpm build # tsup — REQUIRED: `pnpm pack` does not build
pnpm pack # → ztube-observability-<version>.tgz in the cwdImportant
Order matters. pnpm release bumps the version first, then pnpm build before pnpm pack. The build is wired to prepublishOnly, which only fires on npm publish — pnpm pack skips it, so without a fresh build the tarball ships a stale or empty dist/.
pnpm release (changeset && changeset version) is interactive and does not commit — after packing, commit the version bump + CHANGELOG.md + the consumed .changeset/ file. pnpm pack reads the bumped version from package.json for the tarball name.
Verify the tarball before uploading — only the files allowlist ships:
tar -tzf ztube-observability-*.tgz | head -30 # dist/ present, src/example absentNote
The package targets ES2022 with NodeNext modules. Node.js ≥ 22 is required at runtime (enforced by engines, a preinstall guard, and a boot-time check).