---
title: "Fastify"
description: "The plugin shadows Fastify's built-in pino logger on `request.log` and emits one wide event from the onRequest, onResponse and onError hooks."
canonical_url: "https://www.evlog.dev/integrate/frameworks/fastify"
---
# Fastify

> The plugin shadows Fastify's built-in pino logger on `request.log` and emits one wide event from the onRequest, onResponse and onError hooks.

The `evlog/fastify` plugin auto-creates a request-scoped logger accessible via `request.log` and `useLogger()`, emitting a wide event when the response completes.

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

Set up evlog in my Fastify app.

- Install evlog: pnpm add evlog
- Create evlog.config.ts with export default defineEvlog({ service: 'my-api' })
- Call initLogger(toLoggerConfig(config)) at startup, importing config from evlog.config.ts
- Import evlog from 'evlog/fastify' and register with app.register(evlog, toMiddlewareOptions(config))
- Access the logger via request.log in route handlers or useLogger() anywhere
- Use log.set() to accumulate context throughout the request
- Put drain, enrich, include and keep in evlog.config.ts; pass toMiddlewareOptions(config) when registering

Docs: [https://www.evlog.dev/integrate/frameworks/fastify](https://www.evlog.dev/integrate/frameworks/fastify)
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 fastify
```

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

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

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

</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, and the wiring below, for you. See [Configuration](https://www.evlog.dev/reference/configuration).

### 3. Initialize and register the plugin

```typescript [src/index.ts]
import Fastify from 'fastify'
import { initLogger, toLoggerConfig, toMiddlewareOptions } from 'evlog'
import { evlog } from 'evlog/fastify'
import config from '../evlog.config'

initLogger(toLoggerConfig(config))

const app = Fastify({ logger: false })

await app.register(evlog, toMiddlewareOptions(config))

app.get('/health', async (request) => {
  request.log.set({ route: 'health' })
  return { ok: true }
})

await app.listen({ port: 3000 })
```

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

**Using Vite?** 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 the service and the other serializable settings come from the file. It cannot carry the drain, so keep the `initLogger(toLoggerConfig(config))` call: it runs after the plugin's auto-init and replaces it.

</callout>

`request.log` is the evlog wide-event logger and shadows Fastify's built-in pino logger on the request. The pino logger remains accessible via `fastify.log` for server-level structured logging.

## Wide Events

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

```typescript [src/index.ts]
app.get('/users/:id', async (request) => {
  const { id } = request.params as { id: string }

  request.log.set({ user: { id } })

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

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

  return { 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 /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 the request object through your service layer:

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

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/index.ts]
import { findUser } from './services/user'

app.get('/users/:id', async (request) => {
  const { id } = request.params as { id: string }
  const user = await findUser(id)
  return user
})
```

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

## Background work (`log.fork`)

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

```typescript [src/index.ts]
import { evlog, useLogger } from 'evlog/fastify'

app.post('/orders', async (request, reply) => {
  request.log.fork!('fulfill', async () => {
    const log = useLogger()
    log.set({ step: 'ok' })
  })
  return { ok: true }
})
```

## Error Handling

Use `createError` for structured errors with `why`, `fix`, and `link` fields. Fastify captures thrown errors via `onError`:

```typescript [src/index.ts]
import { createError, parseError } from 'evlog'

app.get('/checkout', async (_request, reply) => {
  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',
  })
})

app.setErrorHandler((error, _request, reply) => {
  const parsed = parseError(error)
  reply.status(parsed.status).send({
    message: parsed.message,
    why: parsed.why,
    fix: parsed.fix,
    link: parsed.link,
  })
})
```

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

```bash [Terminal output]
14:58:20 ERROR [my-api] GET /checkout 402 in 3ms
  ├─ error: name=EvlogError message=Payment failed status=402
  └─ 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 plugin options; an inline key replaces the one from the file instead of merging with it:

```typescript [src/index.ts]
import { createAxiomDrain } from 'evlog/axiom'
import { createUserAgentEnricher } from 'evlog/enrichers'

const userAgent = createUserAgentEnricher()

await app.register(evlog, {
  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/index.ts]
import type { DrainContext } from 'evlog'
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())

await app.register(evlog, { 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/index.ts]
await app.register(evlog, {
  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/index.ts]
await app.register(evlog, {
  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 fastify
```

Open [http://localhost:3000](http://localhost:3000) 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/fastify">

Browse the complete Fastify example source on GitHub.

</card>
</card-group>

## Next Steps

- [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/fastify)


## Sitemap

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