Errors and logging
Read one request's log lines together, log a failed Server Action, send every line to your error tracker, and find the run a ticket quotes.
At the end of this page a failed request can be followed from the id a reader quotes to the lines it wrote and the run it started.
What a log line is
createLogger("orders") from @intelligo-dev/core/logger writes one JSON line per call, with the logger’s name as module. The framework’s own packages log the same way, so your lines and its lines read as one stream.
import { createLogger } from "@intelligo-dev/core/logger";
const log = createLogger("orders");
log.info("Order placed", { orderId, workspaceId });
log.error("Payment failed", { error });Every line is redacted before it is written. A credential field is replaced, and anything shaped like a secret is taken out of an error’s text. In production an email address and an id are shortened as well.
| Variable | What it does |
|---|---|
LOG_LEVEL |
fatal, error, warn, info, debug or trace. Unset, production logs at info and everything else at debug. |
LOG_FULL_IDS |
1 writes the ids of runs, requests, jobs and conversations whole in production, so a line can be looked up against its row. Ids of people and workspaces, and emails, stay short. |
Read one request’s lines together
Work wrapped in withLogContext carries its fields on every line it writes, and on every line of the work it starts. A nested call adds to the fields around it, a line’s own data wins over both, and a concurrent request keeps its own.
import { requestIdFrom, withLogContext } from "@intelligo-dev/core/logger";
await withLogContext({ requestId: requestIdFrom(request.headers) }, () =>
handle(request)
);requestIdFrom returns the x-request-id the request arrived with when that is shaped like an id (letters, digits, ., _, : and -, 128 characters at most), and a new one otherwise. A proxy that sets the header therefore gives a request one id on both sides.
You rarely write that call yourself:
- The chat route’s
POSTandDELETErun under the request’s id. - So does every Route Handler wrapped in
withAuth,withWorkspace,withRoleorwithCronSecretfrom@intelligo-dev/next/route. - A chat refusal’s JSON body carries the same id as
requestId, so a reader can quote it and you can search your logs for it.
A job, a script or a route with no guard is the case for wrapping the work yourself.
A Server Action that fails
A Server Action returns its failure to a form, so the error’s own text must not be what it returns. actionFailure from @intelligo-dev/next ends the catch: it logs the error itself, with its stack and cause, under the name you give, and returns the message you chose.
import { actionFailure } from "@intelligo-dev/next";
export async function placeOrder(input: unknown) {
const t = await getTranslations("orders");
try {
const { workspace } = await requireWorkspace();
await orders.place(workspace.id, parse(input));
return { success: true as const };
} catch (error) {
if (isOrderError(error)) return { success: false, error: t(error.code) };
return actionFailure("orders", error, t("errors.generic"));
}
}Handle the errors you have copy for first. A caller the auth guard refused, signed out or not a member, is not a fault: actionFailure returns the message for it and logs nothing.
A Route Handler that fails
A route answers with a status, so the same job has a different shape there. errorResponse from @intelligo-dev/next/route ends the catch: a typed error of the framework’s becomes its status and { "error": <code> }, and anything else is logged whole and answered as a 500 whose body says only internal_error.
import { errorResponse, withWorkspace } from "@intelligo-dev/next/route";
export const GET = withWorkspace<{ params: Promise<{ id: string }> }>(
async (request, { workspace }, { params }) => {
try {
const { id } = await params;
return Response.json(await orders.get(workspace.id, id));
} catch (error) {
if (isOrderError(error)) {
return Response.json({ error: error.code }, { status: 422 });
}
return errorResponse(error);
}
}
);A service’s not_found is a 404, forbidden a 403, invalid_input a 400, a conflict such as already_member a 409, and rate_limited a 429. The client switches on the code; the error’s message stays in the log.
Errors Next.js catches
An error thrown while rendering a page, in a Server Action or in a Route Handler reaches onRequestError in instrumentation.ts. The scaffold’s version logs one line with the route and never the request’s headers or cookies. The route-error boundaries report only what reaches the browser, so this is where a server failure is seen at all.
export const onRequestError: Instrumentation.onRequestError = async (
error,
request,
context
) => {
if (process.env.NEXT_RUNTIME !== "nodejs") return;
const { createLogger } = await import("@intelligo-dev/core/logger");
const failure = error as { message?: unknown; digest?: unknown };
createLogger("server").error("Request failed", {
error:
typeof failure?.message === "string" ? failure.message : String(error),
digest: typeof failure?.digest === "string" ? failure.digest : undefined,
method: request.method,
path: request.path.split("?")[0],
route: context.routePath,
routeType: context.routeType,
});
};The digest is what the browser’s error page shows in production. A reader who quotes it gives you this line.
Send every line to your tracker
setLogSink hands each line the framework and your app write to a function of yours as well as to stdout. Bind it once, in composeIntelligo().
import { setLogSink } from "@intelligo-dev/core/logger";
setLogSink((record) => {
if (record.level === "error") tracker.captureMessage(record.msg, record);
else tracker.addBreadcrumb(record);
});The record is the line as written: level, module, msg, then the context and the data, already redacted. A line below LOG_LEVEL never reaches the sink, and a sink that throws is ignored, so a tracker that is down does not take a request with it. setLogSink(null) unbinds it.
Find the run a ticket quotes
Two ids are easy to confuse.
- The HTTP request’s id is the
requestIdin the log context and in a chat refusal’s body. It names one request to your server. Search your logs for it. - A run has an execution id and a request id of its own:
turn.executionIdandturn.requestIdin the chat transport, andexecutionIdon everyonTurnevent. They name one execution row.
The admin console finds a run by either of the run’s ids. On a workspace’s page, the executions list’s search box takes an execution id or a request id and opens that run: who paid, its tokens, what was held and charged, the provider’s cost, why it was refused or failed, and its conversation. An unsettled execution on the operations page links to the same panel.
To get from one to the other, log the run where it starts. onTurn.start runs inside the request’s log context, so its line carries the HTTP request’s id beside the execution’s:
onTurn: {
start: ({ executionId }) => log.info("Turn started", { executionId }),
},With LOG_FULL_IDS=1 a production line writes both ids whole.