@worknice/instrumentation
v1.68.0
Published
Shared instrumentation management for Worknice applications
Readme
@worknice/instrumentation
Shared instrumentation, logging and correlation ID management for Worknice applications.
Features
- 🔍 Correlation ID Tracking: Request tracing across async boundaries using Node.js AsyncLocalStorage
- 📝 Flushable Logging: Winston loggers that ship to Axiom and the console, and can be drained before a serverless instance freezes
- 📊 Next.js Instrumentation: Error reporting with Axiom
- 🔄 Cross-Service Tracing: Track requests across services (Notebook, MYOB, Micropay, Basics)
Installation
This package is part of the Worknice monorepo and is automatically available to all apps:
pnpm add @worknice/instrumentationGetting Started
App Instrumentation
For Next.js apps, create an instrumentation.ts file in the app root:
// apps/$app-name/instrumentation.ts
export { register, onRequestError } from "@worknice/instrumentation";register()- Initialises instrumentation. Automatically called by Next.js when instrumentation is enabled.onRequestError()- Handles and logs request errors with correlation tracking. Automatically called by Next.js on errors.
Correlation ID Usage
The package provides multiple ways to work with correlation IDs:
Getting the current correlation ID
import { getCorrelationId } from "@worknice/instrumentation";
const correlationId = getCorrelationId();Running code with a specific correlation ID
import { runWithCorrelationId, getCorrelationId } from "@worknice/instrumentation";
await runWithCorrelationId("$correlationId", async () => {
// All async operations here will have access to the correlation ID
const id = getCorrelationId(); // Returns "$correlationId"
});Getting or generating a correlation ID
import { getOrGenerateCorrelationId } from "@worknice/instrumentation";
const { correlationId, isNew } = getOrGenerateCorrelationId();Extracting from HTTP headers
Extract correlation ID from HTTP headers in order:
x-request-idx-correlation-idrequest-idcorrelation-id
import { extractCorrelationIdFromHeaders } from "@worknice/instrumentation";
const correlationId = extractCorrelationIdFromHeaders(request.headers);Logging
createLogger builds a Winston logger that writes to Axiom and the console, stamps every entry with the current correlation ID, and can be flushed on demand.
It is imported from the /logger subpath, not from the package root — see Package layout and the Edge runtime.
// apps/$app-name/src/services/logger.ts
import createLogger from "@worknice/instrumentation/logger";
import config from "@/config";
const logger = createLogger({
axiom: config.axiom,
defaultMeta: {
host: config.baseUrl.hostname,
},
});
export default logger;Options:
axiom—{ dataset, token }. The Axiom transport is only attached when both are present.defaultMeta— merged into every entry.level— defaults todebug.
The returned FlushableLogger is a winston.Logger with an added flush(). The console transport is always attached, so entries reach Vercel's log drain even when Axiom is unconfigured or a delivery fails.
Flushing
The Axiom transport batches entries in memory and ships them about a second after the first one arrives.
Serverless instances are frozen as soon as the response is returned, so on a fast request — an early error, typically — that batch is discarded before it is ever sent.
flush() drains Winston's internal stream and then waits for the transport to deliver.
That includes any ingest request the transport had already started on its own timer, which would otherwise still be on the wire when the instance freezes.
Loggers built by createLogger register themselves in a process-wide registry, so generic code can drain them all without knowing what they are:
import { flushLogs } from "@worknice/instrumentation";
await flushLogs();You rarely need to call this yourself. Three seams already flush for you, covering the ways an invocation normally ends:
| Seam | Covers |
| --- | --- |
| handleRequest in @worknice/js-sdk | Webhook and API route handlers |
| withServerAction | Server actions, including ones that throw or redirect() |
| onRequestError | Errors that reach Next.js uncaught |
Only the first and third are automatic. Server actions get the seam by being wrapped, which is worth doing to every one of them rather than only the ones that log — both halves are cheap when there is nothing to do, and an unwrapped action fails silently:
import { withServerAction } from "@worknice/instrumentation";
export const saveConfig = withServerAction(async (config: Config) => {
// Correlation context is established, and buffered logs are shipped on the way out.
});Work that outlives the response is not covered, because it runs after those seams have already flushed. Drain it yourself:
after(async () => {
try {
await doDeferredWork();
} finally {
await flushLogs();
}
});The same applies to waitUntil callbacks and any promise you deliberately don't await.
registerLogSink is available for loggers not built by this factory. It takes a { flush: () => Promise<void> } and returns an unregister function.
Configuration
Environment Variables
The package supports the following environment variables:
AXIOM_DATASET: Axiom dataset name for error loggingAXIOM_TOKEN: Axiom API token for authenticationNODE_ENV: Environment name (development, staging, production)
These are read directly by onRequestError. Loggers you build with createLogger take their credentials from the axiom option instead, so apps keep passing them through their own config.
When Axiom credentials are not provided, entries still go to the console and flush() becomes a no-op.
The console transport is not a fallback: it is always attached, so logs go to both destinations whenever Axiom is configured.
Architecture
AsyncLocalStorage
The package uses Node.js AsyncLocalStorage to maintain correlation context across async boundaries without explicitly passing IDs through function calls. This allows correlation IDs to automatically flow through:
- GraphQL operations
- Database queries
- API calls
- Background jobs
- Nested async operations
Package layout and the Edge runtime
Every app's src/middleware.ts imports this package and runs on the Edge runtime, which has no node:async_hooks, no streams and no Winston.
Everything reachable from src/index.ts therefore has to be Edge-safe at module scope, which is why:
correlation.tsimportsnode:async_hookslazily, inside a function.instrumentation.tsis a thin shim whoseregister/onRequestErrordynamically import the Node-onlyinstrumentation-node.ts.logSinks.tshas no imports at all. That's what letsserverAction.tsdrain Winston loggers without importing Winston.
logger.ts imports winston and @axiomhq/winston at module scope and cannot follow those patterns, so it is reached only through its subpath and is deliberately absent from src/index.ts.
⚠️ Don't re-export
logger.tsfromsrc/index.ts. A convenience line likeexport { default as createLogger } from "./logger.js";pulls Winston into the module graph of every consumer of the package root — includingmiddleware.ts. Nothing locally will warn you: the barrel type-checks, tests pass, and Node routes run fine. It surfaces as an Edge bundling failure or a bloated middleware bundle at build time, in a file nobody touched.
The rule for anything added here: a module that imports a Node-only dependency at module scope stays out of src/index.ts and is consumed via its subpath. The "./*" entry in exports already makes every module importable
that way, so no packaging change is needed.
Development
Building
pnpm --filter=@worknice/instrumentation buildDevelopment Mode
pnpm --filter=@worknice/instrumentation devTesting & Linting
pnpm --filter=@worknice/instrumentation test:lint
pnpm --filter=@worknice/instrumentation test:types
pnpm --filter=@worknice/instrumentation test:formatUse Cases
Cross-Service Request Tracing
When a request flows through multiple services (e.g., Notebook → MYOB → External API), the correlation ID helps trace the entire request chain:
In Notebook app:
import { getOrGenerateCorrelationId } from "@worknice/instrumentation";
const { correlationId } = getOrGenerateCorrelationId();
await fetch("https://myob-service/api/endpoint", {
headers: {
"x-correlation-id": correlationId,
},
});In MYOB service:
import { extractCorrelationIdFromHeaders, runWithCorrelationId } from "@worknice/instrumentation";
const correlationId = extractCorrelationIdFromHeaders(req.headers);
runWithCorrelationId(correlationId, async () => {
// All operations here share the same correlation ID
await processRequest();
});Background Job Tracking
Track background jobs initiated from web requests:
In API route:
import { getCorrelationId } from "@worknice/instrumentation";
const correlationId = getCorrelationId();
await inngest.send({
name: "process.data",
data: { correlationId, ...payload },
});In Inngest function:
import { runWithCorrelationId } from "@worknice/instrumentation";
export const processData = inngest.createFunction(
{ id: "process-data" },
{ event: "process.data" },
async ({ event }) => {
return runWithCorrelationId(event.data.correlationId, async () => {
// Job execution with correlation tracking
});
}
);Troubleshooting
Correlation ID Not Available
If getCorrelationId() returns undefined:
- Ensure you're within a correlation context (use
runWithCorrelationId) - Verify the context hasn't been lost (e.g., through
setTimeoutwithout binding)
Axiom Logs Not Appearing
- Verify
AXIOM_DATASETandAXIOM_TOKENenvironment variables are set - Check console output on startup for "Axiom error logging enabled" message
- Ensure the Axiom dataset exists and token has write permissions
- Check whether the entries reached Vercel's logs. Everything is written to the console too, so if they are in Vercel but not Axiom, it's a delivery problem — look for
[Logger] Axiom rejected a batch of logs. - If they are in neither, the entry probably never reached a logger built by
createLogger. Check that the code path passes the app's logger rather than falling back toconsole—handleRequestdoes this when nologgeroption is given
Logs Missing Only From Failed Or Fast Requests
The batch was almost certainly discarded when the instance froze. Check that the code path ends at one of the three flushing seams (handleRequest, withServerAction, onRequestError).
Work scheduled with after() or waitUntil, or a promise that isn't awaited, runs past those seams and needs its own await flushLogs().
