---
title: "SvelteKit"
description: "Wire the handle and handleError hooks once, and every SvelteKit request carries a logger on `event.locals.log` until the response ends."
canonical_url: "https://www.evlog.dev/integrate/frameworks/sveltekit"
---
# SvelteKit

> Wire the handle and handleError hooks once, and every SvelteKit request carries a logger on `event.locals.log` until the response ends.

The `evlog/sveltekit` adapter provides `handle` and `handleError` hooks that auto-create a request-scoped logger accessible via `event.locals.log` and `useLogger()`, emitting a wide event when the response completes.

<prompt :actions="["copy","cursor","claude"]" description="Set up evlog in my SvelteKit app" icon="i-simple-icons-svelte">

Set up evlog in my SvelteKit app.

- Install evlog: pnpm add evlog
- Create evlog.config.ts with export default defineEvlog({ service: 'my-api' })
- In hooks.server.ts, call initLogger(toLoggerConfig(config)) and export handle and handleError from createEvlogHooks(toMiddlewareOptions(config))
- Optionally add the evlog/vite plugin for debug stripping and source locations (it reads evlog.config.ts too)
- Access the logger via event.locals.log or useLogger() in routes and services
- Use log.set() to accumulate context, throw createError() for structured errors
- Wide events are auto-emitted when each request completes

Docs: [https://www.evlog.dev/integrate/frameworks/sveltekit](https://www.evlog.dev/integrate/frameworks/sveltekit)
Adapters: [https://www.evlog.dev/integrate/adapters/overview](https://www.evlog.dev/integrate/adapters/overview)

</prompt>

## Quick Start

### 1. Install

<code-group>

```bash [pnpm]
pnpm add evlog
```

```bash [bun]
bun add evlog
```

```bash [yarn]
yarn add evlog
```

```bash [npm]
npm install evlog
```

</code-group>

### 2. Create evlog.config.ts

```typescript [evlog.config.ts]
import { defineEvlog } from 'evlog'

export default defineEvlog({
  service: 'my-api',
})
```

Every option lives in this file: sampling, drain, `enrich`, route filters. `npx evlog init` writes it for you. See [Configuration](https://www.evlog.dev/reference/configuration).

### 3. Create hooks

```typescript [src/hooks.server.ts]
import { initLogger, toLoggerConfig, toMiddlewareOptions } from 'evlog'
import { createEvlogHooks } from 'evlog/sveltekit'
import config from '../evlog.config'

initLogger(toLoggerConfig(config))

export const { handle, handleError } = createEvlogHooks(toMiddlewareOptions(config))
```

`toLoggerConfig` passes the logger options of the file and `toMiddlewareOptions` the request options, so the sampling, drain, `enrich` and route filters all apply.

<callout color="info" icon="i-custom-vite">

**Optional:** the [`evlog/vite` plugin](https://www.evlog.dev/reference/vite-plugin) strips `log.debug()` from production builds and injects source locations. It reads `evlog.config.ts` too, so add it without a service and let the file set it. The `initLogger` call above runs after its auto-initialization and replaces it.

</callout>

### 4. Type your locals

```typescript [src/app.d.ts]
import type { RequestLogger } from 'evlog'

declare global {
  namespace App {
    interface Locals {
      log: RequestLogger
    }
  }
}

export {}
```

## Wide Events

Build up context progressively through your handler. One request = one wide event:

```typescript [src/routes/api/users/[id]/+server.ts]
import { json } from '@sveltejs/kit'
import type { RequestHandler } from './$types'

export const GET: RequestHandler = async ({ locals, params }) => {
  locals.log.set({ user: { id: params.id } })

  const user = await db.findUser(params.id)
  locals.log.set({ user: { name: user.name, plan: user.plan } })

  const orders = await db.findOrders(params.id)
  locals.log.set({ orders: { count: orders.length, totalRevenue: sum(orders) } })

  return json({ user, orders })
}
```

All fields are merged into a single wide event emitted when the request completes:

```bash [Terminal output]
14:58:15 INFO [my-api] GET /api/users/usr_123 200 in 12ms
  ├─ orders: count=2 totalRevenue=6298
  ├─ user: id=usr_123 name=Alice plan=pro
  └─ requestId: 4a8ff3a8-...
```

## useLogger()

Use `useLogger()` to access the request-scoped logger from anywhere in the call stack without passing locals through your service layer:

```typescript [src/lib/services/user.ts]
import { useLogger } from 'evlog/sveltekit'

export async function findUser(id: string) {
  const log = useLogger()
  log.set({ user: { id } })

  const user = await db.findUser(id)
  log.set({ user: { name: user.name, plan: user.plan } })

  return user
}
```

```typescript [src/routes/api/users/[id]/+server.ts]
import { json } from '@sveltejs/kit'
import { findUser } from '$lib/services/user'
import type { RequestHandler } from './$types'

export const GET: RequestHandler = async ({ params }) => {
  const user = await findUser(params.id)
  return json(user)
}
```

Both `event.locals.log` and `useLogger()` return the same logger instance. `useLogger()` uses `AsyncLocalStorage` to propagate the logger across async boundaries.

## Background work (`log.fork`)

Use `locals.log.fork(label, fn)` for a child wide event. See [After emit](https://www.evlog.dev/learn/wide-events#after-emit-sealing-and-background-work) in Wide events.

```typescript [src/routes/api/orders/+server.ts]
import { useLogger } from 'evlog/sveltekit'
import type { RequestHandler } from './$types'

export const POST: RequestHandler = async ({ locals }) => {
  locals.log.fork!('process', async () => {
    const log = useLogger()
    log.set({ step: 'done' })
  })
  return new Response(JSON.stringify({ ok: true }))
}
```

## Error Handling

Use `createError` for structured errors with `why`, `fix`, and `link` fields. The `handleError` hook captures thrown errors automatically:

```typescript [src/routes/api/checkout/+server.ts]
import { json } from '@sveltejs/kit'
import { createError } from 'evlog'
import type { RequestHandler } from './$types'

export const POST: RequestHandler = async ({ locals, request }) => {
  const { cartId } = await request.json()
  locals.log.set({ cart: { id: cartId } })

  throw createError({
    message: 'Payment failed',
    status: 402,
    why: 'Card declined by issuer',
    fix: 'Try a different payment method',
    link: 'https://docs.example.com/payments/declined',
  })
}
```

The error is captured and logged with both the custom context and structured error fields:

```bash [Terminal output]
14:58:20 ERROR [my-api] POST /api/checkout 402 in 3ms
  ├─ error: name=EvlogError message=Payment failed status=402
  ├─ cart: id=cart_456
  └─ requestId: 880a50ac-...
```

## Configuration

Every option goes in `evlog.config.ts`. See the [Configuration reference](https://www.evlog.dev/reference/configuration) for the full list.

## Drain & Enrichers

Set `drain` and `enrich` in `evlog.config.ts` so they reach the app through `toMiddlewareOptions(config)`. You can also pass them inline in the hooks options; an inline key replaces the one from the file instead of merging with it:

```typescript [src/hooks.server.ts]
import { createEvlogHooks } from 'evlog/sveltekit'
import { createAxiomDrain } from 'evlog/axiom'
import { createUserAgentEnricher } from 'evlog/enrichers'

const userAgent = createUserAgentEnricher()

export const { handle, handleError } = createEvlogHooks({
  drain: createAxiomDrain(),
  enrich: (ctx) => {
    userAgent(ctx)
    ctx.event.region = process.env.FLY_REGION
  },
})
```

### Pipeline (Batching & Retry)

For production, wrap your adapter with `createDrainPipeline` to batch events and retry on failure:

```typescript [src/hooks.server.ts]
import type { DrainContext } from 'evlog'
import { createEvlogHooks } from 'evlog/sveltekit'
import { createAxiomDrain } from 'evlog/axiom'
import { createDrainPipeline } from 'evlog/pipeline'

const pipeline = createDrainPipeline<DrainContext>({
  batch: { size: 50, intervalMs: 5000 },
  retry: { maxAttempts: 3 },
})
const drain = pipeline(createAxiomDrain())

export const { handle, handleError } = createEvlogHooks({ drain })
```

<callout color="info" icon="i-lucide-info">

Call `drain.flush()` on server shutdown to ensure all buffered events are sent. See the [Pipeline docs](https://www.evlog.dev/extend/drain-pipeline) for all options.

</callout>

## Tail Sampling

Use `keep` to force-retain specific events regardless of head sampling:

```typescript [src/hooks.server.ts]
export const { handle, handleError } = createEvlogHooks({
  drain: createAxiomDrain(),
  keep: (ctx) => {
    if (ctx.duration && ctx.duration > 2000) ctx.shouldKeep = true
  },
})
```

## Route Filtering

Control which routes are logged with `include` and `exclude` patterns:

```typescript [src/hooks.server.ts]
export const { handle, handleError } = createEvlogHooks({
  include: ['/api/**'],
  exclude: ['/_internal/**', '/health'],
  routes: {
    '/api/auth/**': { service: 'auth-service' },
    '/api/payment/**': { service: 'payment-service' },
  },
})
```

## Run Locally

```bash [Terminal]
git clone https://github.com/evloghq/evlog.git
cd evlog
pnpm install
pnpm example sveltekit
```

Open [http://localhost:5173](http://localhost:5173) to explore the interactive test UI.

<card-group>
<card icon="i-simple-icons-github" title="Source Code" to="https://github.com/evloghq/evlog/tree/main/examples/sveltekit">

Browse the complete SvelteKit example source on GitHub.

</card>
</card-group>

## Next Steps

Deepen your **SvelteKit** integration:

- [Wide Events](https://www.evlog.dev/learn/wide-events): Design comprehensive events with context layering
- [Adapters](https://www.evlog.dev/integrate/adapters/overview): Send logs to Axiom, Sentry, PostHog, and more
- [Sampling](https://www.evlog.dev/learn/sampling): Control log volume with head and tail sampling
- [Structured Errors](https://www.evlog.dev/learn/structured-errors): Throw errors with `why`, `fix`, and `link` fields

---

- [Source Code](https://github.com/evloghq/evlog/tree/main/examples/sveltekit)


## Sitemap

See the full [sitemap](https://www.evlog.dev/sitemap.md) for all pages.
