Skip to main content

SvelteKit hooks: one log line per request, and unexpected errors logged, traced and given an id.

Server only: requestLog writes one line per page or API request and skips assets and data requests; unexpectedErrors logs a crash, records it on the request's span and hands the error page its trace id as the error id.

14:02:15.020 ERROR [Server] Unhandled error { errorId: '1ac71cdacfc998b028cb0a12aee24333', path: '/api/stats' }
Error: The database didn't answer in time.
    at load (src/routes/api/stats/+server.ts:12:11)
14:02:15.020 ERROR [Http] GET /api/stats 500 12ms

Usage

hooks.server.ts
import { sequence } from "@sveltejs/kit/hooks";

import { requestLog, unexpectedErrors } from "@zedensix/ui/server/hooks";
import { Logger } from "@zedensix/ui/server/logger";

export const handle = sequence(requestLog(new Logger("Http")));

export const handleError = unexpectedErrors(
	new Logger("Server"),
	"Something went wrong.",
);