create-wervt 0.2.0 → 0.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1249 @@
1
+ ---
2
+ name: review-logging-patterns
3
+ description: Review code for logging patterns and suggest evlog adoption. Optionally use the evlog CLI, shipped with the evlog package (`evlog init` to wire evlog, `evlog agents` to write the conventions into AGENTS.md, `evlog map` to score entry-point coverage, `--baseline` to gate regressions in CI) on Nuxt, Nitro, Next.js, TanStack Start, Hono, Express, and Fastify. Guides setup on those plus SvelteKit, React Router, NestJS, Express, Fastify, Elysia, oRPC, Cloudflare Workers, AWS Lambda, Astro, and standalone TypeScript. Detects console.log spam, unstructured errors, and missing context. Covers wide events, structured errors, drain adapters (Axiom, OTLP, HyperDX, PostHog, Sentry, Better Stack, Datadog, Loki, ClickHouse, NuxtHub, Memory), sampling, enrichers, and AI SDK integration.
4
+ license: MIT
5
+ metadata:
6
+ author: HugoRCD
7
+ version: '0.9'
8
+ ---
9
+
10
+ # Review logging patterns
11
+
12
+ Review and improve logging patterns in TypeScript/JavaScript codebases. Transform scattered console.logs into structured wide events and convert generic errors into self-documenting structured errors.
13
+
14
+ ## When to Use
15
+
16
+ - Setting up evlog in a new or existing project (any supported framework)
17
+ - Reviewing code for logging best practices
18
+ - Converting console.log statements to structured logging
19
+ - Improving error handling with better context
20
+ - Configuring log draining, sampling, or enrichment
21
+
22
+ ## Quick Reference
23
+
24
+ | Working on... | Resource |
25
+ | ------------------------- | --------------------------------------------------------------------------------------------------------------- |
26
+ | Setup (CLI) | [`evlog init`](https://www.evlog.dev/cli/init): wire evlog into the project |
27
+ | Project conventions (CLI) | [`evlog agents`](https://www.evlog.dev/cli/agents): write the evlog block into the project's AGENTS.md |
28
+ | Coverage map (CLI) | [`evlog map`](https://www.evlog.dev/cli/map): score dark entry points |
29
+ | CI gating (CLI) | [`evlog map --min-score / --baseline`](https://www.evlog.dev/cli/ci): gate regressions |
30
+ | Wide events patterns | [references/wide-events.md](references/wide-events.md) |
31
+ | Error handling | [references/structured-errors.md](references/structured-errors.md) |
32
+ | Code review checklist | [references/code-review.md](references/code-review.md) |
33
+ | Drain pipeline | [references/drain-pipeline.md](references/drain-pipeline.md) |
34
+ | Audit logs | [build-audit-logs](../build-audit-logs/SKILL.md) skill + [docs](https://www.evlog.dev/use-cases/audit/overview) |
35
+
36
+ ## Audit logs
37
+
38
+ For security-sensitive actions (auth, billing, admin, data export), use evlog's audit layer: a typed `audit` field on wide events, not a parallel logger. See the **`build-audit-logs`** skill for end-to-end setup (`log.audit`, `withAudit`, denials, `auditEnricher`, `auditOnly`, `signed`, `mockAudit`).
39
+
40
+ ```typescript
41
+ log.audit({
42
+ action: 'invoice.refund',
43
+ actor: { type: 'user', id: user.id },
44
+ target: { type: 'invoice', id: invoice.id },
45
+ outcome: 'success',
46
+ })
47
+ ```
48
+
49
+ Docs: https://www.evlog.dev/use-cases/audit/overview
50
+
51
+ ## Installation
52
+
53
+ ```bash
54
+ npm install evlog
55
+ ```
56
+
57
+ ## Use the CLI (recommended on Nuxt, Nitro, Next.js, TanStack Start, Hono, Express, Fastify)
58
+
59
+ The `evlog` executable ships with the `evlog` package: `pnpm evlog`, `npx evlog`, `bunx evlog`. It runs `@evlog/cli` when installed and fetches it on demand otherwise (no dependency added to the project), so it works on a project with nothing yet. Early but worth trying. It reads the project on disk (no traffic, no config). On the seven supported frameworks it covers the whole loop: **wire evlog in** (`init`), **score coverage** (`map`), **lock the score in CI** (`--min-score`, `--baseline`). If the CLI is unavailable, the framework has no adapter yet, or the user declines, continue with the manual sections below; the skill does not depend on it. **Ask before installing anything**.
60
+
61
+ ### 1. Setup: `evlog init`
62
+
63
+ On a project that doesn't use evlog yet, prefer `init` over hand-writing the setup, since it detects the framework, reads what the project already has, and generates config, drains, enrichers, and extras in one pass. It is fully scriptable for agents:
64
+
65
+ ```bash
66
+ # preview everything without writing (always start here)
67
+ npx evlog init --dry-run --yes
68
+
69
+ # then apply — flags instead of prompts
70
+ npx evlog init --yes \
71
+ --service my-app \
72
+ --drain fs \
73
+ --prodDrain axiom \
74
+ --extras enrichers,pipeline,sampling \
75
+ --sampling medium
76
+ ```
77
+
78
+ Useful flags: `--framework` (override detection: `nuxt`, `nitro`, `next`, `tanstack-start`, `hono`, `express`, `fastify`), `--prodDrain` (comma-separated: `axiom`, `otlp`, `posthog`, `sentry`, `better-stack`, `datadog`, `hyperdx`), `--extras` (`enrichers`, `pipeline`, `sampling`, `vite`, `error-catalog`, `audit-catalog`, `ai`, `better-auth`), `--enrichers`, `--sampling` (traffic tier: `all`, `low`, `medium`, `high`, `very-high`), `--apps` (monorepo: which workspace packages), `--no-install`. Review the `--dry-run` output with the user before applying. Docs: https://www.evlog.dev/cli/init
79
+
80
+ ### 2. Score: `evlog map`
81
+
82
+ ```bash
83
+ npx evlog map --no-write
84
+ # agents: npx evlog map --json --no-write
85
+ ```
86
+
87
+ What you get:
88
+
89
+ - A project score and which entry points are still dark
90
+ - **FIX FIRST**: the three most valuable places to fix
91
+ - **GOING FURTHER**: opportunities (catalogs, audit coverage, AI logging, auth identity) that never cost points
92
+ - Per-file inspect: `npx evlog map <file> --no-write` shows the shape the handler could take
93
+ - Re-run after fixes and watch the score move
94
+
95
+ Work FIX FIRST in order, keep changes minimal (`useLogger()`, `log.set()`, `log.audit()`, `createError({ why, fix })`), then re-run with `--no-write`. Omit `--no-write` only when the user wants `evlog.map.json` written.
96
+
97
+ ### 3. Lock it in CI: `--min-score` and `--baseline`
98
+
99
+ On GitHub Actions, suggest the [evlog action](https://github.com/evloghq/action) (`uses: evloghq/action@v1` with `min-score`): it scans the pull request base itself, so no map file has to be committed, and puts regressions on the diff and in one comment. The commands below are the same gate from a `run:` step.
100
+
101
+ After fixing, propose making the score durable. This is where the CLI earns its keep:
102
+
103
+ ```bash
104
+ # in CI, after pnpm add -D @evlog/cli (pinned by the lockfile; ask first)
105
+ pnpm exec evlog map --min-score 80 # absolute gate: exits 1 below the threshold
106
+ pnpm exec evlog map --baseline # ratchet: exits 1 if this PR made things worse
107
+ ```
108
+
109
+ `--baseline` compares the fresh scan against the committed `evlog.map.json`, **per entry point and per requirement**, so a refactor that instruments one route and breaks another fails even if the total score is unchanged. Disabling a passing check with a comment counts as a regression too. New uninstrumented routes are listed as `NEW AND DARK` without failing. Workflow: commit `evlog.map.json` once, add the `--baseline` run to CI, then re-run `map` without `--baseline` to accept an intentional change. Docs: https://www.evlog.dev/cli/ci
110
+
111
+ Early days: adapters and rules are still evolving; expect scores to move between releases. Docs: https://www.evlog.dev/cli/map · Rules: https://www.evlog.dev/cli/rules
112
+
113
+ ---
114
+
115
+ ## Framework Setup
116
+
117
+ ### Nuxt
118
+
119
+ ```typescript
120
+ // nuxt.config.ts
121
+ export default defineNuxtConfig({
122
+ modules: ['evlog/nuxt'],
123
+ evlog: {
124
+ env: { service: 'my-app' },
125
+ include: ['/api/**'],
126
+ },
127
+ })
128
+ ```
129
+
130
+ `useLogger`, `log`, and `parseError` are **auto-imported**. `createError` is not: a bare one resolves to h3's, which drops `why`, `fix`, and `link`. Import it from `evlog`.
131
+
132
+ ```typescript
133
+ // server/api/checkout.post.ts — no imports needed
134
+ export default defineEventHandler(async (event) => {
135
+ const log = useLogger(event)
136
+ log.set({ user: { id: user.id, plan: user.plan } })
137
+ return { success: true }
138
+ })
139
+ ```
140
+
141
+ Drain, enrich, and tail sampling use Nitro hooks in server plugins:
142
+
143
+ ```typescript
144
+ // server/plugins/evlog-drain.ts
145
+ import { createAxiomDrain } from 'evlog/axiom'
146
+
147
+ export default defineNitroPlugin((nitroApp) => {
148
+ nitroApp.hooks.hook('evlog:drain', createAxiomDrain())
149
+ })
150
+ ```
151
+
152
+ Client transport (auto-configured Vue plugin):
153
+
154
+ ```typescript
155
+ // nuxt.config.ts
156
+ evlog: {
157
+ transport: { enabled: true }, // logs sent to /api/_evlog/ingest
158
+ }
159
+ ```
160
+
161
+ Client-side: `log`, `setIdentity`, `clearIdentity` are auto-imported in components.
162
+
163
+ ### Next.js
164
+
165
+ **Step 1: Create central config.** All exports come from here:
166
+
167
+ ```typescript
168
+ // lib/evlog.ts
169
+ import type { DrainContext } from 'evlog'
170
+ import { createEvlog } from 'evlog/next'
171
+ import { createUserAgentEnricher, createRequestSizeEnricher } from 'evlog/enrichers'
172
+ import { createDrainPipeline } from 'evlog/pipeline'
173
+
174
+ const enrichers = [createUserAgentEnricher(), createRequestSizeEnricher()]
175
+ const pipeline = createDrainPipeline<DrainContext>({ batch: { size: 50, intervalMs: 5000 } })
176
+ const drain = pipeline(createAxiomDrain({ dataset: 'logs', apiKey: process.env.AXIOM_API_KEY! }))
177
+
178
+ export const { withEvlog, useLogger, log, createError } = createEvlog({
179
+ service: 'my-app',
180
+ sampling: {
181
+ rates: { info: 10 },
182
+ keep: [{ status: 400 }, { duration: 1000 }],
183
+ },
184
+ routes: {
185
+ '/api/auth/**': { service: 'auth-service' },
186
+ '/api/checkout/**': { service: 'checkout-service' },
187
+ },
188
+ keep: (ctx) => {
189
+ const user = ctx.context.user as { premium?: boolean } | undefined
190
+ if (user?.premium) ctx.shouldKeep = true
191
+ },
192
+ enrich: (ctx) => {
193
+ for (const enricher of enrichers) enricher(ctx)
194
+ },
195
+ drain,
196
+ })
197
+ ```
198
+
199
+ **Step 2: Wrap route handlers** with `withEvlog()`:
200
+
201
+ ```typescript
202
+ // app/api/checkout/route.ts
203
+ import { withEvlog, useLogger } from '@/lib/evlog'
204
+
205
+ export const POST = withEvlog(async (request: Request) => {
206
+ const log = useLogger() // Zero arguments — uses AsyncLocalStorage
207
+ log.set({ user: { id: 'user_123', plan: 'enterprise' } })
208
+ log.set({ cart: { items: 3, total: 14999 } })
209
+ return Response.json({ success: true })
210
+ })
211
+ ```
212
+
213
+ **Step 3: Server Actions.** Same `withEvlog()` wrapper:
214
+
215
+ ```typescript
216
+ // app/actions.ts
217
+ 'use server'
218
+ import { withEvlog, useLogger } from '@/lib/evlog'
219
+
220
+ export const checkout = withEvlog(async (formData: FormData) => {
221
+ const log = useLogger()
222
+ log.set({ action: 'checkout', source: 'server-action' })
223
+ return { success: true }
224
+ })
225
+ ```
226
+
227
+ **Step 4: Middleware** (optional, sets `x-request-id` + timing headers):
228
+
229
+ ```typescript
230
+ // proxy.ts
231
+ import { evlogMiddleware } from 'evlog/next'
232
+ export const proxy = evlogMiddleware()
233
+ export const config = { matcher: ['/api/:path*'] }
234
+ ```
235
+
236
+ **Step 5: Client Provider.** Wrap the root layout:
237
+
238
+ ```tsx
239
+ // app/layout.tsx
240
+ import { EvlogProvider } from 'evlog/next/client'
241
+
242
+ export default function Layout({ children }: { children: React.ReactNode }) {
243
+ return (
244
+ <html lang="en">
245
+ <body>
246
+ <EvlogProvider
247
+ service="my-app"
248
+ transport={{ enabled: true, endpoint: '/api/evlog/ingest' }}
249
+ >
250
+ {children}
251
+ </EvlogProvider>
252
+ </body>
253
+ </html>
254
+ )
255
+ }
256
+ ```
257
+
258
+ **Step 6: Client logging.** In any client component:
259
+
260
+ ```tsx
261
+ 'use client'
262
+ import { log, setIdentity, clearIdentity } from 'evlog/next/client'
263
+
264
+ setIdentity({ userId: 'usr_123' })
265
+ log.info({ action: 'checkout_click' })
266
+ clearIdentity()
267
+ ```
268
+
269
+ **Step 7 (optional): Instrumentation.** Startup plus global `onRequestError` (SSR/RSC errors outside `withEvlog`). Use `defineNodeInstrumentation(() => import('./lib/evlog'))` in root `instrumentation.ts` to gate Node + cache the import, **or** write `register`/`onRequestError` manually. Both are valid. For custom logic, wrap evlog’s `register`/`onRequestError` inside `lib/evlog.ts` (compose with your own init or metrics), then re-export.
270
+
271
+ Export `createInstrumentation()` from `lib/evlog.ts` alongside `createEvlog()`. See framework docs for coexistence with `lockLogger`.
272
+
273
+ **Step 8: Client ingest endpoint.** Receives client logs:
274
+
275
+ ```typescript
276
+ // app/api/evlog/ingest/route.ts
277
+ import { NextRequest } from 'next/server'
278
+
279
+ const VALID_LEVELS = ['info', 'error', 'warn', 'debug'] as const
280
+
281
+ export async function POST(request: NextRequest) {
282
+ const origin = request.headers.get('origin')
283
+ const host = request.headers.get('host')
284
+ if (origin && new URL(origin).host !== host) {
285
+ return Response.json({ error: 'Invalid origin' }, { status: 403 })
286
+ }
287
+ const body = await request.json()
288
+ if (!body?.timestamp || !body?.level || !VALID_LEVELS.includes(body.level)) {
289
+ return Response.json({ error: 'Invalid payload' }, { status: 400 })
290
+ }
291
+ const { service: _, ...sanitized } = body
292
+ console.log('[CLIENT LOG]', JSON.stringify({ ...sanitized, service: 'my-app', source: 'client' }))
293
+ return new Response(null, { status: 204 })
294
+ }
295
+ ```
296
+
297
+ ### SvelteKit
298
+
299
+ ```typescript
300
+ // src/hooks.server.ts
301
+ import { initLogger } from 'evlog'
302
+ import { createEvlogHooks } from 'evlog/sveltekit'
303
+
304
+ initLogger({ env: { service: 'my-app' } })
305
+
306
+ export const { handle, handleError } = createEvlogHooks()
307
+ ```
308
+
309
+ Access the logger via `event.locals.log` in route handlers or `useLogger()` from anywhere in the call stack:
310
+
311
+ ```typescript
312
+ // src/routes/api/users/[id]/+server.ts
313
+ import { json } from '@sveltejs/kit'
314
+
315
+ export const GET = ({ locals, params }) => {
316
+ locals.log.set({ user: { id: params.id } })
317
+ return json({ id: params.id })
318
+ }
319
+ ```
320
+
321
+ ```typescript
322
+ import { useLogger } from 'evlog/sveltekit'
323
+
324
+ async function findUsers() {
325
+ const log = useLogger()
326
+ log.set({ db: { query: 'SELECT * FROM users' } })
327
+ }
328
+ ```
329
+
330
+ Full pipeline with drain, enrich, and tail sampling:
331
+
332
+ ```typescript
333
+ import { createAxiomDrain } from 'evlog/axiom'
334
+
335
+ export const { handle, handleError } = createEvlogHooks({
336
+ include: ['/api/**'],
337
+ drain: createAxiomDrain(),
338
+ enrich: (ctx) => {
339
+ ctx.event.region = process.env.FLY_REGION
340
+ },
341
+ keep: (ctx) => {
342
+ if (ctx.duration && ctx.duration > 2000) ctx.shouldKeep = true
343
+ },
344
+ })
345
+ ```
346
+
347
+ ### Nitro v3
348
+
349
+ ```typescript
350
+ // nitro.config.ts
351
+ import { defineConfig } from 'nitro'
352
+ import evlog from 'evlog/nitro/v3'
353
+
354
+ export default defineConfig({
355
+ modules: [evlog({ env: { service: 'my-api' } })],
356
+ })
357
+ ```
358
+
359
+ ```typescript
360
+ // routes/api/checkout.post.ts
361
+ import { defineHandler } from 'nitro/h3'
362
+ import { useLogger } from 'evlog/nitro/v3'
363
+
364
+ export default defineHandler(async (event) => {
365
+ const log = useLogger(event)
366
+ log.set({ action: 'checkout' })
367
+ return { ok: true }
368
+ })
369
+ ```
370
+
371
+ ### TanStack Start
372
+
373
+ TanStack Start uses Nitro v3. Install evlog and add a `nitro.config.ts`:
374
+
375
+ ```typescript
376
+ // nitro.config.ts
377
+ import { defineConfig } from 'nitro'
378
+ import evlog from 'evlog/nitro/v3'
379
+
380
+ export default defineConfig({
381
+ experimental: { asyncContext: true },
382
+ modules: [evlog({ env: { service: 'my-app' } })],
383
+ })
384
+ ```
385
+
386
+ Add the error handling middleware to `__root.tsx`:
387
+
388
+ ```typescript
389
+ // src/routes/__root.tsx
390
+ import { createMiddleware } from '@tanstack/react-start'
391
+ import { evlogErrorHandler } from 'evlog/nitro/v3'
392
+
393
+ export const Route = createRootRoute({
394
+ server: {
395
+ middleware: [createMiddleware().server(evlogErrorHandler)],
396
+ },
397
+ })
398
+ ```
399
+
400
+ Use `useRequest()` from `nitro/context` to access the logger:
401
+
402
+ ```typescript
403
+ import { useRequest } from 'nitro/context'
404
+ import type { RequestLogger } from 'evlog'
405
+
406
+ const req = useRequest()
407
+ const log = req.context.log as RequestLogger
408
+ log.set({ user: { id: 'user_123' } })
409
+ ```
410
+
411
+ ### Nitro v2
412
+
413
+ ```typescript
414
+ // nitro.config.ts
415
+ import { defineNitroConfig } from 'nitropack/config'
416
+ import evlog from 'evlog/nitro'
417
+
418
+ export default defineNitroConfig({
419
+ modules: [evlog({ env: { service: 'my-api' } })],
420
+ })
421
+ ```
422
+
423
+ Import `useLogger` from `evlog/nitro` in routes.
424
+
425
+ ### NestJS
426
+
427
+ ```typescript
428
+ // src/app.module.ts
429
+ import { Module } from '@nestjs/common'
430
+ import { EvlogModule } from 'evlog/nestjs'
431
+
432
+ @Module({
433
+ imports: [EvlogModule.forRoot()],
434
+ })
435
+ export class AppModule {}
436
+ ```
437
+
438
+ `EvlogModule.forRoot()` registers a global middleware. Use `useLogger()` to access the request-scoped logger from any controller or service:
439
+
440
+ ```typescript
441
+ import { useLogger } from 'evlog/nestjs'
442
+
443
+ async function findUsers() {
444
+ const log = useLogger()
445
+ log.set({ db: { query: 'SELECT * FROM users' } })
446
+ }
447
+ ```
448
+
449
+ Full pipeline with drain, enrich, and tail sampling:
450
+
451
+ ```typescript
452
+ import { createAxiomDrain } from 'evlog/axiom'
453
+
454
+ EvlogModule.forRoot({
455
+ include: ['/api/**'],
456
+ drain: createAxiomDrain(),
457
+ enrich: (ctx) => {
458
+ ctx.event.region = process.env.FLY_REGION
459
+ },
460
+ keep: (ctx) => {
461
+ if (ctx.duration && ctx.duration > 2000) ctx.shouldKeep = true
462
+ },
463
+ })
464
+ ```
465
+
466
+ For async configuration with NestJS DI, use `forRootAsync()`:
467
+
468
+ ```typescript
469
+ EvlogModule.forRootAsync({
470
+ imports: [ConfigModule],
471
+ inject: [ConfigService],
472
+ useFactory: (config) => ({
473
+ drain: createAxiomDrain({ apiKey: config.get('AXIOM_API_KEY') }),
474
+ }),
475
+ })
476
+ ```
477
+
478
+ ### Express
479
+
480
+ ```typescript
481
+ import express from 'express'
482
+ import { initLogger } from 'evlog'
483
+ import { evlog, useLogger } from 'evlog/express'
484
+
485
+ initLogger({ env: { service: 'my-api' } })
486
+
487
+ const app = express()
488
+ app.use(evlog())
489
+
490
+ app.get('/api/users', (req, res) => {
491
+ req.log.set({ users: { count: 42 } })
492
+ res.json({ users: [] })
493
+ })
494
+ ```
495
+
496
+ Use `useLogger()` to access the logger from anywhere in the call stack without passing `req`:
497
+
498
+ ```typescript
499
+ import { useLogger } from 'evlog/express'
500
+
501
+ async function findUsers() {
502
+ const log = useLogger()
503
+ log.set({ db: { query: 'SELECT * FROM users' } })
504
+ }
505
+ ```
506
+
507
+ Full pipeline with drain, enrich, and tail sampling:
508
+
509
+ ```typescript
510
+ import { createAxiomDrain } from 'evlog/axiom'
511
+
512
+ app.use(
513
+ evlog({
514
+ include: ['/api/**'],
515
+ drain: createAxiomDrain(),
516
+ enrich: (ctx) => {
517
+ ctx.event.region = process.env.FLY_REGION
518
+ },
519
+ keep: (ctx) => {
520
+ if (ctx.duration && ctx.duration > 2000) ctx.shouldKeep = true
521
+ },
522
+ }),
523
+ )
524
+ ```
525
+
526
+ ### Hono
527
+
528
+ ```typescript
529
+ import { Hono } from 'hono'
530
+ import { initLogger } from 'evlog'
531
+ import { evlog, type EvlogVariables } from 'evlog/hono'
532
+
533
+ initLogger({ env: { service: 'my-api' } })
534
+
535
+ const app = new Hono<EvlogVariables>()
536
+ app.use(evlog())
537
+
538
+ app.get('/api/users', (c) => {
539
+ const log = c.get('log')
540
+ log.set({ users: { count: 42 } })
541
+ return c.json({ users: [] })
542
+ })
543
+ ```
544
+
545
+ Access the logger via `c.get('log')` in handlers. Use `useLogger()` from `evlog/hono` in the layers underneath (services, repositories) where `c` is not in hand. Both return the same logger:
546
+
547
+ ```typescript
548
+ import { useLogger } from 'evlog/hono'
549
+
550
+ async function findUsers() {
551
+ const log = useLogger()
552
+ log.set({ db: { query: 'SELECT * FROM users' } })
553
+ }
554
+ ```
555
+
556
+ On Cloudflare Workers, `useLogger()` needs the `nodejs_compat` (or `nodejs_als`) compatibility flag; `c.get('log')` works with or without it.
557
+
558
+ Structured errors: throw `createError()`, then in `app.onError` use `parseError()` and pass `parsed.status as ContentfulStatusCode` to `c.json()` (Hono types the status argument as `ContentfulStatusCode`, not `number`).
559
+
560
+ ```typescript
561
+ import { createError, parseError } from 'evlog'
562
+ import type { ContentfulStatusCode } from 'hono/utils/http-status'
563
+
564
+ app.onError((error, c) => {
565
+ c.get('log').error(error)
566
+ const parsed = parseError(error)
567
+ return c.json(
568
+ { message: parsed.message, why: parsed.why, fix: parsed.fix, link: parsed.link },
569
+ parsed.status as ContentfulStatusCode,
570
+ )
571
+ })
572
+ ```
573
+
574
+ Full pipeline with drain, enrich, and tail sampling:
575
+
576
+ ```typescript
577
+ import { createAxiomDrain } from 'evlog/axiom'
578
+
579
+ app.use(
580
+ evlog({
581
+ include: ['/api/**'],
582
+ drain: createAxiomDrain(),
583
+ enrich: (ctx) => {
584
+ ctx.event.region = process.env.FLY_REGION
585
+ },
586
+ keep: (ctx) => {
587
+ if (ctx.duration && ctx.duration > 2000) ctx.shouldKeep = true
588
+ },
589
+ }),
590
+ )
591
+ ```
592
+
593
+ ### Fastify
594
+
595
+ ```typescript
596
+ import Fastify from 'fastify'
597
+ import { initLogger } from 'evlog'
598
+ import { evlog, useLogger } from 'evlog/fastify'
599
+
600
+ initLogger({ env: { service: 'my-api' } })
601
+
602
+ const app = Fastify({ logger: false })
603
+ await app.register(evlog)
604
+
605
+ app.get('/api/users', async (request) => {
606
+ request.log.set({ users: { count: 42 } })
607
+ return { users: [] }
608
+ })
609
+ ```
610
+
611
+ `request.log` is the evlog wide-event logger (shadows Fastify's built-in pino logger on the request). Fastify's pino logger remains accessible via `fastify.log`.
612
+
613
+ Use `useLogger()` to access the logger from anywhere in the call stack without passing `request`:
614
+
615
+ ```typescript
616
+ import { useLogger } from 'evlog/fastify'
617
+
618
+ async function findUsers() {
619
+ const log = useLogger()
620
+ log.set({ db: { query: 'SELECT * FROM users' } })
621
+ }
622
+ ```
623
+
624
+ Full pipeline with drain, enrich, and tail sampling:
625
+
626
+ ```typescript
627
+ import { createAxiomDrain } from 'evlog/axiom'
628
+
629
+ await app.register(evlog, {
630
+ include: ['/api/**'],
631
+ drain: createAxiomDrain(),
632
+ enrich: (ctx) => {
633
+ ctx.event.region = process.env.FLY_REGION
634
+ },
635
+ keep: (ctx) => {
636
+ if (ctx.duration && ctx.duration > 2000) ctx.shouldKeep = true
637
+ },
638
+ })
639
+ ```
640
+
641
+ ### Elysia
642
+
643
+ ```typescript
644
+ import { Elysia } from 'elysia'
645
+ import { initLogger } from 'evlog'
646
+ import { evlog, useLogger } from 'evlog/elysia'
647
+
648
+ initLogger({ env: { service: 'my-api' } })
649
+
650
+ const app = new Elysia()
651
+ .use(evlog())
652
+ .get('/api/users', ({ log }) => {
653
+ log.set({ users: { count: 42 } })
654
+ return { users: [] }
655
+ })
656
+ .listen(3000)
657
+ ```
658
+
659
+ Use `useLogger()` to access the logger from anywhere in the call stack:
660
+
661
+ ```typescript
662
+ import { useLogger } from 'evlog/elysia'
663
+
664
+ async function findUsers() {
665
+ const log = useLogger()
666
+ log.set({ db: { query: 'SELECT * FROM users' } })
667
+ }
668
+ ```
669
+
670
+ Full pipeline with drain, enrich, and tail sampling:
671
+
672
+ ```typescript
673
+ import { createAxiomDrain } from 'evlog/axiom'
674
+
675
+ app.use(
676
+ evlog({
677
+ include: ['/api/**'],
678
+ drain: createAxiomDrain(),
679
+ enrich: (ctx) => {
680
+ ctx.event.region = process.env.FLY_REGION
681
+ },
682
+ keep: (ctx) => {
683
+ if (ctx.duration && ctx.duration > 2000) ctx.shouldKeep = true
684
+ },
685
+ }),
686
+ )
687
+ ```
688
+
689
+ ### React Router
690
+
691
+ ```typescript
692
+ // react-router.config.ts
693
+ import type { Config } from '@react-router/dev/config'
694
+
695
+ export default {
696
+ future: {
697
+ v8_middleware: true,
698
+ },
699
+ } satisfies Config
700
+ ```
701
+
702
+ ```typescript
703
+ // app/root.tsx
704
+ import { initLogger } from 'evlog'
705
+ import { evlog } from 'evlog/react-router'
706
+
707
+ initLogger({ env: { service: 'my-api' } })
708
+
709
+ export const middleware: Route.MiddlewareFunction[] = [evlog()]
710
+ ```
711
+
712
+ Access the logger via `context.get(loggerContext)` in loaders and actions:
713
+
714
+ ```typescript
715
+ // app/routes/api.users.$id.tsx
716
+ import { loggerContext } from 'evlog/react-router'
717
+
718
+ export async function loader({ params, context }: Route.LoaderArgs) {
719
+ const log = context.get(loggerContext)
720
+ log.set({ user: { id: params.id } })
721
+ return { users: [] }
722
+ }
723
+ ```
724
+
725
+ Use `useLogger()` to access the logger from anywhere in the call stack without passing context:
726
+
727
+ ```typescript
728
+ import { useLogger } from 'evlog/react-router'
729
+
730
+ async function findUsers() {
731
+ const log = useLogger()
732
+ log.set({ db: { query: 'SELECT * FROM users' } })
733
+ }
734
+ ```
735
+
736
+ Full pipeline with drain, enrich, and tail sampling:
737
+
738
+ ```typescript
739
+ import { createAxiomDrain } from 'evlog/axiom'
740
+
741
+ export const middleware: Route.MiddlewareFunction[] = [
742
+ evlog({
743
+ include: ['/api/**'],
744
+ drain: createAxiomDrain(),
745
+ enrich: (ctx) => {
746
+ ctx.event.region = process.env.FLY_REGION
747
+ },
748
+ keep: (ctx) => {
749
+ if (ctx.duration && ctx.duration > 2000) ctx.shouldKeep = true
750
+ },
751
+ }),
752
+ ]
753
+ ```
754
+
755
+ ### oRPC
756
+
757
+ ```typescript
758
+ import { os } from '@orpc/server'
759
+ import { RPCHandler } from '@orpc/server/fetch'
760
+ import { initLogger } from 'evlog'
761
+ import { evlog, withEvlog, type EvlogOrpcContext } from 'evlog/orpc'
762
+
763
+ initLogger({ env: { service: 'my-rpc' } })
764
+
765
+ const base = os.$context<EvlogOrpcContext>().use(evlog())
766
+
767
+ const router = {
768
+ ping: base.handler(({ context }) => {
769
+ context.log.set({ pinged: true })
770
+ return { ok: true }
771
+ }),
772
+ }
773
+
774
+ const handler = withEvlog(new RPCHandler(router))
775
+
776
+ export default async function fetch(request: Request) {
777
+ const { matched, response } = await handler.handle(request, { prefix: '/rpc' })
778
+ return matched ? response : new Response('Not Found', { status: 404 })
779
+ }
780
+ ```
781
+
782
+ `withEvlog()` wraps the handler so each matched request emits one wide event; `os.use(evlog())` exposes `context.log` on every procedure that descends from `base` and tags the wide event with `operation` (the procedure path joined with `.`).
783
+
784
+ Use `useLogger()` to access the logger from utility modules:
785
+
786
+ ```typescript
787
+ import { useLogger } from 'evlog/orpc'
788
+
789
+ async function chargeCard(amount: number) {
790
+ const log = useLogger()
791
+ log.set({ payment: { amount } })
792
+ }
793
+ ```
794
+
795
+ Full pipeline with drain, enrich, and tail sampling:
796
+
797
+ ```typescript
798
+ import { createAxiomDrain } from 'evlog/axiom'
799
+
800
+ const handler = withEvlog(new RPCHandler(router), {
801
+ include: ['/rpc/**'],
802
+ drain: createAxiomDrain(),
803
+ enrich: (ctx) => {
804
+ ctx.event.region = process.env.FLY_REGION
805
+ },
806
+ keep: (ctx) => {
807
+ if (ctx.duration && ctx.duration > 2000) ctx.shouldKeep = true
808
+ },
809
+ })
810
+ ```
811
+
812
+ ### Cloudflare Workers
813
+
814
+ ```typescript
815
+ import { initWorkersLogger, withEvlog } from 'evlog/workers'
816
+
817
+ initWorkersLogger({ env: { service: 'edge-api' } })
818
+
819
+ export default withEvlog(async (request, _env, _ctx, log) => {
820
+ log.set({ action: 'handle_request' })
821
+ return Response.json({ ok: true })
822
+ })
823
+ ```
824
+
825
+ `withEvlog` emits one wide event per request when the handler returns, with no manual `log.emit()`. Async drains are registered with `waitUntil` so they survive the response; streaming responses defer the emit until the body completes. `requestId` comes from `x-request-id` (fallback `cf-ray`); `method`, `path`, `cf-ray`, `traceparent`, and the safe subset of `request.cf` are captured automatically. It accepts the same options (`drain`, `enrich`, `keep`, `include`, `exclude`, `routes`) as every other integration. For manual control (scheduled handlers, queues), `createWorkersLogger(request)` + `log.emit()` remains available. No ALS-based `useLogger()` on Workers, so pass `log` explicitly.
826
+
827
+ ### AWS Lambda
828
+
829
+ Lambda has no HTTP middleware lifecycle, so evlog behaves like standalone TypeScript, with one critical rule: **one logger per invocation**, never a shared module-level logger (Lambda reuses execution environments, so a shared instance leaks fields between invocations).
830
+
831
+ ```typescript
832
+ import { initLogger, createLogger } from 'evlog'
833
+
834
+ initLogger({ env: { service: 'my-fn' } }) // once at module load (cold start)
835
+
836
+ export async function handler(event: SQSEvent) {
837
+ for (const record of event.Records) {
838
+ const log = createLogger({ messageId: record.messageId })
839
+ try {
840
+ log.set({ queue: { source: record.eventSourceARN } })
841
+ await processMessage(record)
842
+ } catch (error) {
843
+ log.error(error as Error)
844
+ throw error
845
+ } finally {
846
+ log.emit()
847
+ }
848
+ }
849
+ }
850
+ ```
851
+
852
+ ### Astro
853
+
854
+ ```typescript
855
+ // src/middleware.ts
856
+ import { defineMiddleware } from 'astro:middleware'
857
+ import { initLogger, createRequestLogger } from 'evlog'
858
+
859
+ initLogger({ env: { service: 'my-astro-app' } })
860
+
861
+ export const onRequest = defineMiddleware(async ({ request, locals }, next) => {
862
+ const url = new URL(request.url)
863
+ const log = createRequestLogger({ method: request.method, path: url.pathname })
864
+ locals.log = log
865
+
866
+ try {
867
+ const response = await next()
868
+ log.emit()
869
+ return response
870
+ } catch (error) {
871
+ log.error(error instanceof Error ? error : new Error(String(error)))
872
+ log.emit()
873
+ throw error
874
+ }
875
+ })
876
+ ```
877
+
878
+ Type `locals.log` in `src/env.d.ts` (`interface Locals { log: RequestLogger }`). Pair with the Vite plugin (below) for auto-imports and build-time DX.
879
+
880
+ ### Vite Plugin (any Vite-based framework)
881
+
882
+ For any Vite-based project (SvelteKit, Astro, SolidStart, React+Vite, etc.), use the Vite plugin for auto-init, auto-imports, and build-time features:
883
+
884
+ ```typescript
885
+ // vite.config.ts
886
+ import evlog from 'evlog/vite'
887
+
888
+ export default defineConfig({
889
+ plugins: [
890
+ evlog({
891
+ service: 'my-app',
892
+ autoImports: true, // auto-import log, createEvlogError, parseError
893
+ strip: ['debug'], // remove log.debug() in production
894
+ sourceLocation: true, // inject file:line in dev + prod
895
+ client: {
896
+ // client-side logging
897
+ transport: { endpoint: '/api/logs' },
898
+ },
899
+ }),
900
+ ],
901
+ })
902
+ ```
903
+
904
+ Server-side middleware (drain, enrich, keep, routes) is still configured in the framework integration (e.g., `evlog()` middleware for Hono/Express/SvelteKit). The Vite plugin handles build-time DX only.
905
+
906
+ ### Standalone TypeScript
907
+
908
+ ```typescript
909
+ import { initLogger, createRequestLogger } from 'evlog'
910
+
911
+ initLogger({ env: { service: 'my-worker', environment: 'production' } })
912
+
913
+ const log = createRequestLogger({ jobId: job.id })
914
+ log.set({ source: job.source, recordsSynced: 150 })
915
+ log.emit() // Manual emit required in standalone
916
+ ```
917
+
918
+ ---
919
+
920
+ ## Configuration Options
921
+
922
+ All options work in Nuxt (`evlog` key), Nitro (passed to `evlog()`), Next.js (`createEvlog()`), and standalone (`initLogger()`).
923
+
924
+ | Option | Type | Default | Description |
925
+ | ------------------------- | ---------------------------------------- | -------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- |
926
+ | `env.service` / `service` | `string` | `'app'` | Service name in logs |
927
+ | `enabled` | `boolean` | `true` | Global toggle (no-ops when false) |
928
+ | `pretty` | `boolean` | `true` in dev | Pretty tree format vs JSON |
929
+ | `silent` | `boolean` | `false` | Suppress console output. Events still go to drains |
930
+ | `include` | `string[]` | All routes | Route glob patterns to log |
931
+ | `exclude` | `string[]` | None | Route patterns to exclude (takes precedence) |
932
+ | `routes` | `Record<string, { service }>` | -- | Route-specific service names |
933
+ | `minLevel` | `'debug' \| 'info' \| 'warn' \| 'error'` | `'debug'` | Hard threshold for the global `log` API and client `log` (not request wide events). Use `sampling.rates` for probabilistic volume on requests |
934
+ | `sampling.rates` | `object` | -- | Head sampling: `{ info: 10, warn: 50 }` (0-100%) |
935
+ | `sampling.keep` | `array` | -- | Tail sampling: `[{ status: 400 }, { duration: 1000 }]` |
936
+ | `drain` | `(ctx) => void` | -- | Drain callback (Next.js, standalone) |
937
+ | `enrich` | `(ctx) => void` | -- | Enrich callback (Next.js) |
938
+ | `keep` | `(ctx) => void` | -- | Custom tail sampling callback (Next.js) |
939
+ | `redact` | `boolean \| RedactConfig` | `true` in production | Enabled by default in production. `false` to disable. Object for fine-grained control |
940
+
941
+ ### Nitro Hooks (Nuxt, Nitro v2/v3)
942
+
943
+ | Hook | When | Use |
944
+ | ----------------- | ------------------------------------------- | -------------------------------- |
945
+ | `evlog:drain` | After enrichment | Send events to external services |
946
+ | `evlog:enrich` | After emit, before console output and drain | Add derived context |
947
+ | `evlog:emit:keep` | During emit | Custom tail sampling logic |
948
+ | `close` | Server shutdown | Flush drain pipeline buffers |
949
+
950
+ ---
951
+
952
+ ## Drain Adapters
953
+
954
+ | Adapter | Import | Env Vars |
955
+ | --------------------- | ------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
956
+ | Axiom | `evlog/axiom` | `AXIOM_API_KEY`, `AXIOM_DATASET` |
957
+ | OTLP | `evlog/otlp` | `OTLP_ENDPOINT` (or the standard `OTEL_EXPORTER_OTLP_[LOGS_]ENDPOINT`, `_HEADERS`, `_COMPRESSION`, `_PROTOCOL`, `OTEL_RESOURCE_ATTRIBUTES`). `protocol: 'http/protobuf'` sends binary protobuf. `semanticConventions: true` adds OTel attribute names (`http.*`, `exception.*`, `gen_ai.*`) |
958
+ | HyperDX | `evlog/hyperdx` | `HYPERDX_API_KEY` (optional `HYPERDX_OTLP_ENDPOINT`; defaults to `https://in-otel.hyperdx.io`) |
959
+ | PostHog | `evlog/posthog` | `POSTHOG_API_KEY`, `POSTHOG_HOST` |
960
+ | Sentry | `evlog/sentry` | `SENTRY_DSN` |
961
+ | Better Stack | `evlog/better-stack` | `BETTER_STACK_API_KEY` |
962
+ | Datadog | `evlog/datadog` | `DD_API_KEY` or `DATADOG_API_KEY`, optional `DD_SITE` / `DATADOG_LOGS_URL` |
963
+ | Grafana Loki | `evlog/loki` | `LOKI_ENDPOINT`, optional `LOKI_API_KEY` + `LOKI_USER` (Grafana Cloud) or `LOKI_TENANT_ID` (multi-tenant) |
964
+ | ClickHouse | `evlog/clickhouse` | `CLICKHOUSE_ENDPOINT`, optional `CLICKHOUSE_USER` / `CLICKHOUSE_PASSWORD` / `CLICKHOUSE_DATABASE` / `CLICKHOUSE_TABLE` |
965
+ | File System | `evlog/fs` | None (local file system) |
966
+ | Memory | `evlog/memory` | None (in-process ring buffer; optional `EVLOG_MEMORY_STORE`, `EVLOG_MEMORY_MAX_EVENTS`). Read back with `readMemoryLogs()`, ideal for dev-only log endpoints agents can query |
967
+ | NuxtHub | `@evlog/nuxthub` (separate package, Nuxt module) | None: stores wide events in the NuxtHub database with retention-based cleanup (set `evlog.retention: '7d'` in the module options; accepts `d`/`h`/`m`) |
968
+ | HTTP (browser ingest) | `evlog/http` | None (configure `endpoint` in code). `evlog/browser` is deprecated; same API, removed next major |
969
+
970
+ Use canonical env var names (e.g. `AXIOM_API_KEY`, `BETTER_STACK_API_KEY`), and the same names work in every framework.
971
+
972
+ Setup pattern per framework:
973
+
974
+ ```typescript
975
+ // Nuxt/Nitro: server/plugins/evlog-drain.ts
976
+ import { createAxiomDrain } from 'evlog/axiom'
977
+ export default defineNitroPlugin((nitroApp) => {
978
+ nitroApp.hooks.hook('evlog:drain', createAxiomDrain())
979
+ })
980
+
981
+ // Hono / Express / Elysia: pass drain in middleware options
982
+ import { createAxiomDrain } from 'evlog/axiom'
983
+ app.use(evlog({ drain: createAxiomDrain() }))
984
+
985
+ // Fastify: pass drain in plugin options
986
+ import { createAxiomDrain } from 'evlog/axiom'
987
+ await app.register(evlog, { drain: createAxiomDrain() })
988
+
989
+ // NestJS: pass drain in module options
990
+ import { createAxiomDrain } from 'evlog/axiom'
991
+ EvlogModule.forRoot({ drain: createAxiomDrain() })
992
+
993
+ // Next.js: pass drain to createEvlog()
994
+ import { createAxiomDrain } from 'evlog/axiom'
995
+ import { createDrainPipeline } from 'evlog/pipeline'
996
+ const pipeline = createDrainPipeline<DrainContext>({ batch: { size: 50 } })
997
+ const drain = pipeline(createAxiomDrain())
998
+ // then: createEvlog({ ..., drain })
999
+
1000
+ // Standalone: pass drain to initLogger()
1001
+ initLogger({ env: { service: 'my-app' }, drain: createAxiomDrain() })
1002
+ ```
1003
+
1004
+ See [references/drain-pipeline.md](references/drain-pipeline.md) for batching, retry, and buffer overflow config.
1005
+
1006
+ ---
1007
+
1008
+ ## Enrichers
1009
+
1010
+ Built-in: `createUserAgentEnricher()`, `createGeoEnricher()`, `createRequestSizeEnricher()`, `createTraceContextEnricher()`, all from `evlog/enrichers`. Each accepts `{ overwrite?: boolean }` (default `false`). Use `createDefaultEnrichers()` to compose all four in one call:
1011
+
1012
+ ```typescript
1013
+ import { createDefaultEnrichers } from 'evlog/enrichers'
1014
+ app.use(evlog({ enrich: createDefaultEnrichers() }))
1015
+ ```
1016
+
1017
+ ```typescript
1018
+ // Nuxt/Nitro: server/plugins/evlog-enrich.ts
1019
+ import { createUserAgentEnricher, createGeoEnricher } from 'evlog/enrichers'
1020
+ export default defineNitroPlugin((nitroApp) => {
1021
+ const enrichers = [createUserAgentEnricher(), createGeoEnricher()]
1022
+ nitroApp.hooks.hook('evlog:enrich', (ctx) => {
1023
+ for (const enricher of enrichers) enricher(ctx)
1024
+ })
1025
+ })
1026
+
1027
+ // Next.js: in lib/evlog.ts
1028
+ createEvlog({
1029
+ enrich: (ctx) => {
1030
+ for (const enricher of enrichers) enricher(ctx)
1031
+ ctx.event.region = process.env.VERCEL_REGION
1032
+ },
1033
+ })
1034
+ ```
1035
+
1036
+ ---
1037
+
1038
+ ## Auto-Redaction (PII Protection)
1039
+
1040
+ Built-in redaction scrubs sensitive data from wide events **before** console output and **before** any drain sees the data. **Enabled by default in production** (`NODE_ENV === 'production'`), disabled in development. Uses **smart partial masking**, preserving enough context for debugging.
1041
+
1042
+ ```typescript
1043
+ // Disable in production (opt-out)
1044
+ evlog: { redact: false }
1045
+
1046
+ // Add custom paths on top of built-ins
1047
+ evlog: {
1048
+ redact: {
1049
+ paths: ['user.password', 'headers.authorization'],
1050
+ }
1051
+ }
1052
+
1053
+ // Only specific built-ins
1054
+ evlog: {
1055
+ redact: {
1056
+ builtins: ['email', 'creditCard'],
1057
+ }
1058
+ }
1059
+
1060
+ // No built-ins, only custom (uses flat [REDACTED] replacement)
1061
+ evlog: {
1062
+ redact: {
1063
+ builtins: false,
1064
+ paths: ['user.ssn'],
1065
+ patterns: [/SECRET_\w+/g],
1066
+ }
1067
+ }
1068
+ ```
1069
+
1070
+ **Built-in patterns** with smart masking output:
1071
+
1072
+ | Pattern | Example Input | Masked Output |
1073
+ | ------------ | ----------------------- | ----------------- |
1074
+ | `creditCard` | `4111111111111111` | `****1111` |
1075
+ | `email` | `alice@example.com` | `a***@***.com` |
1076
+ | `ipv4` | `192.168.1.100` | `***.***.***.100` |
1077
+ | `phone` | `+33 6 12 34 56 78` | `+33 ****5678` |
1078
+ | `jwt` | `eyJhbGciOi...` | `eyJ***.***` |
1079
+ | `bearer` | `Bearer sk_live_abc...` | `Bearer ***` |
1080
+ | `iban` | `FR76 3000 6000 ...189` | `FR76****189` |
1081
+
1082
+ Works in all frameworks: Nuxt (`evlog` config), Nitro (`evlog()` module options), Next.js (`createEvlog()`), standalone (`initLogger()`), and all middleware integrations (Hono, Express, Fastify, Elysia, NestJS).
1083
+
1084
+ ---
1085
+
1086
+ ## AI SDK Integration
1087
+
1088
+ Capture token usage, tool calls, model info, streaming metrics, tool execution timing, cost estimation, and embedding metadata from the Vercel AI SDK into wide events. Import from `evlog/ai`. Requires `ai >=6.0.168 <8.0.0` as a peer dependency.
1089
+
1090
+ ### Basic setup (middleware)
1091
+
1092
+ ```typescript
1093
+ import { createAILogger } from 'evlog/ai'
1094
+
1095
+ const log = useLogger(event) // or any RequestLogger
1096
+ const ai = createAILogger(log)
1097
+
1098
+ const result = streamText({
1099
+ model: ai.wrap('anthropic/claude-sonnet-4.6'), // accepts string or model object
1100
+ messages,
1101
+ })
1102
+ ```
1103
+
1104
+ `ai.wrap()` uses model middleware to transparently capture all LLM calls. Works with `generateText`, `streamText`, and `ToolLoopAgent`.
1105
+
1106
+ ### Telemetry integration (deeper observability)
1107
+
1108
+ For tool execution timing, success/failure tracking, and total generation wall time, add `createEvlogIntegration()`:
1109
+
1110
+ ```typescript
1111
+ import { createAILogger, createEvlogIntegration } from 'evlog/ai'
1112
+
1113
+ const ai = createAILogger(log)
1114
+
1115
+ const agent = new ToolLoopAgent({
1116
+ model: ai.wrap('anthropic/claude-sonnet-4.6'),
1117
+ tools: { searchWeb, queryDatabase },
1118
+ stopWhen: stepCountIs(5),
1119
+ telemetry: {
1120
+ integrations: [createEvlogIntegration(ai)],
1121
+ },
1122
+ })
1123
+ ```
1124
+
1125
+ This adds `ai.tools` (per-tool `{ name, durationMs, success, error? }`) and `ai.totalDurationMs` to the wide event.
1126
+
1127
+ ### Embeddings
1128
+
1129
+ ```typescript
1130
+ const { embedding, usage } = await embed({ model: embeddingModel, value: query })
1131
+ ai.captureEmbed({ usage, model: 'text-embedding-3-small', dimensions: 1536 })
1132
+ ```
1133
+
1134
+ For `embedMany`, pass the batch count:
1135
+
1136
+ ```typescript
1137
+ ai.captureEmbed({ usage, model: 'text-embedding-3-small', count: documents.length })
1138
+ ```
1139
+
1140
+ ### Cost estimation
1141
+
1142
+ Pass a pricing map to get `ai.estimatedCost` in the wide event:
1143
+
1144
+ ```typescript
1145
+ const ai = createAILogger(log, {
1146
+ cost: {
1147
+ 'claude-sonnet-4.6': { input: 3, output: 15 },
1148
+ 'gpt-4o': { input: 2.5, output: 10 },
1149
+ },
1150
+ })
1151
+ ```
1152
+
1153
+ ### Wide event `ai` field
1154
+
1155
+ Includes: `calls`, `model`, `provider`, `inputTokens`, `outputTokens`, `totalTokens`, `cacheReadTokens`, `reasoningTokens`, `finishReason`, `toolCalls`, `steps`, `msToFirstChunk`, `msToFinish`, `tokensPerSecond`, `error`, `tools` (via telemetry integration), `totalDurationMs` (via telemetry integration), `embedding` (via `captureEmbed`), `estimatedCost` (via `cost` option).
1156
+
1157
+ Anti-patterns to detect:
1158
+
1159
+ | Anti-Pattern | Fix |
1160
+ | -------------------------------------- | ------------------------------------------------------------ |
1161
+ | Manual token tracking in `onFinish` | `ai.wrap()`: middleware captures automatically |
1162
+ | `console.log('tokens:', result.usage)` | `ai.wrap()`: structured `ai.*` fields in wide event |
1163
+ | No AI observability | Add `createAILogger(log)` + `ai.wrap()` |
1164
+ | No tool execution timing | Add `createEvlogIntegration(ai)` to `telemetry.integrations` |
1165
+ | Manual cost calculation | Use `cost` option in `createAILogger()` |
1166
+
1167
+ ---
1168
+
1169
+ ## Related Capabilities (pointers)
1170
+
1171
+ Recommend these when the review surfaces the matching need. Each has full docs on evlog.dev:
1172
+
1173
+ | Need spotted | evlog answer | Docs |
1174
+ | ------------------------------------------------------------------------- | ------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------- |
1175
+ | Auth'd user identity missing from events (Better Auth apps) | `evlog/better-auth`: `identifyUser()`, `createAuthMiddleware()`, client identity sync | https://www.evlog.dev/use-cases/better-auth/overview |
1176
+ | Ad-hoc field names drifting across the codebase | Typed fields + error/audit catalogs (`evlog/catalog`) | https://www.evlog.dev/learn/typed-fields · https://www.evlog.dev/learn/catalogs |
1177
+ | Cross-cutting hooks (request start/finish, client logs, logger extension) | Plugins: `definePlugin` | https://www.evlog.dev/extend/plugins |
1178
+ | Tail logs live during dev / build a log viewer | `createStreamDrain` (`evlog/stream`, SSE) + `readFsLogs` / `tailFsLogs` (`evlog/fs`) | https://www.evlog.dev/extend/stream |
1179
+ | Agents need to query logs over HTTP in dev | Memory adapter + `readMemoryLogs()` behind a dev-only endpoint | https://www.evlog.dev/integrate/adapters/self-hosted/memory |
1180
+
1181
+ ---
1182
+
1183
+ ## Structured Errors
1184
+
1185
+ ```typescript
1186
+ import { createError } from 'evlog' // required in Nuxt too: a bare createError is h3's
1187
+
1188
+ // Minimal
1189
+ throw createError({ message: 'Database connection failed', status: 500 })
1190
+
1191
+ // Standard
1192
+ throw createError({ message: 'Payment failed', status: 402, why: 'Card declined by issuer' })
1193
+
1194
+ // Complete
1195
+ throw createError({
1196
+ message: 'Payment failed',
1197
+ status: 402,
1198
+ why: 'Card declined by issuer - insufficient funds',
1199
+ fix: 'Please use a different payment method or contact your bank',
1200
+ link: 'https://docs.example.com/payments/declined',
1201
+ cause: originalError,
1202
+ })
1203
+
1204
+ // Backend-only context (wide events / drains — never HTTP body or parseError())
1205
+ throw createError({
1206
+ message: 'Not allowed',
1207
+ status: 403,
1208
+ why: 'Insufficient permissions',
1209
+ internal: { correlationId: 'req_abc', resourceId: 'proj_123' },
1210
+ })
1211
+ ```
1212
+
1213
+ Frontend: extract user-facing fields with `parseError()` (`internal` is never returned to clients):
1214
+
1215
+ ```typescript
1216
+ import { parseError } from 'evlog'
1217
+
1218
+ const error = parseError(err)
1219
+ // error.message, error.status, error.why, error.fix, error.link
1220
+ ```
1221
+
1222
+ See [references/structured-errors.md](references/structured-errors.md) for common patterns and templates.
1223
+
1224
+ ---
1225
+
1226
+ ## Anti-Patterns to Detect
1227
+
1228
+ | Anti-Pattern | Fix |
1229
+ | ------------------------------------------------ | ------------------------------------------------------------------------------------- |
1230
+ | Multiple `console.log` in one function | Single wide event with `log.set()` |
1231
+ | `throw new Error('...')` | `throw createError({ message, status, why, fix })` |
1232
+ | `console.error(e); throw e` | `log.error(e); throw createError(...)` |
1233
+ | No logging in request handlers | Add `useLogger(event)` / `useLogger()` / `createRequestLogger()` |
1234
+ | Flat log data `{ uid, n, t }` | Grouped objects: `{ user: {...}, cart: {...} }` |
1235
+ | Logging sensitive data `log.set({ user: body })` | Explicit fields: `{ user: { id: body.id, plan: body.plan } }` + enable `redact: true` |
1236
+ | Putting support-only IDs in `why` / `message` | Use `createError({ ..., internal: { ... } })` for non-user-facing diagnostics |
1237
+
1238
+ See [references/code-review.md](references/code-review.md) for the full checklist.
1239
+
1240
+ ---
1241
+
1242
+ ## Loading Reference Files
1243
+
1244
+ Load based on what you're working on, and **do not load all at once**:
1245
+
1246
+ - Designing wide events → [references/wide-events.md](references/wide-events.md)
1247
+ - Improving errors → [references/structured-errors.md](references/structured-errors.md)
1248
+ - Full code review → [references/code-review.md](references/code-review.md)
1249
+ - Drain pipeline setup → [references/drain-pipeline.md](references/drain-pipeline.md)