create-wervt 0.1.0 → 0.2.1
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.
- package/package.json +1 -1
- package/template/.claude/skills/review-logging-patterns/SKILL.md +1249 -0
- package/template/.claude/skills/review-logging-patterns/references/code-review.md +342 -0
- package/template/.claude/skills/review-logging-patterns/references/drain-pipeline.md +166 -0
- package/template/.claude/skills/review-logging-patterns/references/structured-errors.md +468 -0
- package/template/.claude/skills/review-logging-patterns/references/wide-events.md +340 -0
- package/template/.claude/skills/wervt-logs/SKILL.md +77 -0
- package/template/AGENTS.md +22 -0
- package/template/package.json +1 -1
|
@@ -0,0 +1,342 @@
|
|
|
1
|
+
# Code Review Checklist
|
|
2
|
+
|
|
3
|
+
Use this checklist when reviewing code for logging best practices and evlog adoption.
|
|
4
|
+
|
|
5
|
+
## Prefer `evlog map` when you can
|
|
6
|
+
|
|
7
|
+
On **Nuxt, Nitro, Next.js App Router, TanStack Start, Hono, Express, and Fastify**, start with the `evlog` CLI (it ships with the `evlog` package) if the user is open to it: one command finds dark entry points and names the fixes:
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
npx evlog map --no-write
|
|
11
|
+
npx evlog map <file> --no-write # suggested shape for one entry point
|
|
12
|
+
```
|
|
13
|
+
|
|
14
|
+
**Requirements** (move the score) map to the anti-patterns below:
|
|
15
|
+
|
|
16
|
+
| Map rule id | Weight | What it expects | Related anti-pattern |
|
|
17
|
+
| --------------------- | ------ | ------------------------------------ | ------------------------------ |
|
|
18
|
+
| `wide-event` | 40 | `useLogger()` / request logger | No logging in handlers |
|
|
19
|
+
| `audit` | 25 | `log.audit(...)` on sensitive routes | Missing audit on auth/billing |
|
|
20
|
+
| `structured-errors` | 20 | `createError({ why, fix })` | `throw new Error('...')` |
|
|
21
|
+
| `page-error-handling` | 20 | fetch error handling on pages | Unhandled page fetches |
|
|
22
|
+
| `context` | 15 | `log.set(...)` | Flat / missing request context |
|
|
23
|
+
| `error-handling` | 15 | log or rethrow in `catch` | `console.error(e); throw e` |
|
|
24
|
+
|
|
25
|
+
**Opportunities** (never cost points; fire only when the project already uses the feature). Surface them as suggestions, not defects:
|
|
26
|
+
|
|
27
|
+
| Map rule id | Fires when | Related skill section |
|
|
28
|
+
| ---------------- | ------------------------------------------------------------------- | ---------------------------------- |
|
|
29
|
+
| `error-catalog` | A catalog is declared and the same inline error appears in 2+ files | Related Capabilities → catalogs |
|
|
30
|
+
| `audit-coverage` | The project records audits and a state-changing handler has none | Audit logs |
|
|
31
|
+
| `ai-logging` | `ai` is a dependency and the AI SDK is called without `evlog/ai` | AI SDK Integration |
|
|
32
|
+
| `auth-identity` | `better-auth` is a dependency without `evlog/better-auth` | Related Capabilities → Better Auth |
|
|
33
|
+
|
|
34
|
+
Full rule reference: https://www.evlog.dev/cli/rules
|
|
35
|
+
|
|
36
|
+
Map tells you the **shape** is present, not that the context is useful at runtime. Keep the scans below for frameworks without adapters, for quality of context, drains, redaction, and AI SDK usage. If the user skips the CLI, use this checklist alone.
|
|
37
|
+
|
|
38
|
+
## Quick Scan
|
|
39
|
+
|
|
40
|
+
Run through these checks first to identify improvement opportunities:
|
|
41
|
+
|
|
42
|
+
### 1. Console Statement Audit
|
|
43
|
+
|
|
44
|
+
Search for these patterns:
|
|
45
|
+
|
|
46
|
+
```typescript
|
|
47
|
+
// ❌ Patterns to find and transform
|
|
48
|
+
console.log(...)
|
|
49
|
+
console.error(...)
|
|
50
|
+
console.warn(...)
|
|
51
|
+
console.info(...)
|
|
52
|
+
console.debug(...)
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
**Questions to ask:**
|
|
56
|
+
|
|
57
|
+
- Are there multiple console statements in one function?
|
|
58
|
+
- Are they logging request/response data?
|
|
59
|
+
- Could they be consolidated into a wide event?
|
|
60
|
+
|
|
61
|
+
### 2. Error Pattern Audit
|
|
62
|
+
|
|
63
|
+
Search for these patterns:
|
|
64
|
+
|
|
65
|
+
```typescript
|
|
66
|
+
// ❌ Generic errors
|
|
67
|
+
throw new Error('...')
|
|
68
|
+
throw Error('...')
|
|
69
|
+
|
|
70
|
+
// ❌ Re-throwing without context
|
|
71
|
+
catch (error) {
|
|
72
|
+
throw error
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
// ❌ Logging and throwing
|
|
76
|
+
catch (error) {
|
|
77
|
+
console.error(error)
|
|
78
|
+
throw error
|
|
79
|
+
}
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
**Questions to ask:**
|
|
83
|
+
|
|
84
|
+
- Does the error message explain what happened?
|
|
85
|
+
- Is there a `why` explaining the root cause?
|
|
86
|
+
- Is there a `fix` suggesting a solution?
|
|
87
|
+
- Is the original error preserved as `cause`?
|
|
88
|
+
|
|
89
|
+
### 3. Request Handler Audit
|
|
90
|
+
|
|
91
|
+
For each API route/handler, check:
|
|
92
|
+
|
|
93
|
+
```typescript
|
|
94
|
+
// ❌ Missing request context
|
|
95
|
+
export default defineEventHandler(async (event) => {
|
|
96
|
+
// No logging at all, or scattered console.logs
|
|
97
|
+
})
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
**Questions to ask:**
|
|
101
|
+
|
|
102
|
+
- Is there a request-scoped logger?
|
|
103
|
+
- Is context accumulated throughout the request?
|
|
104
|
+
- Is there a single emit at the end?
|
|
105
|
+
|
|
106
|
+
## Detailed Review
|
|
107
|
+
|
|
108
|
+
### Console.log Transformations
|
|
109
|
+
|
|
110
|
+
#### Single Debug Log
|
|
111
|
+
|
|
112
|
+
```typescript
|
|
113
|
+
// ❌ Before
|
|
114
|
+
console.log('Processing user:', userId)
|
|
115
|
+
|
|
116
|
+
// ✅ After - if part of a larger operation
|
|
117
|
+
log.set({ user: { id: userId } })
|
|
118
|
+
|
|
119
|
+
// ✅ After - if standalone debug
|
|
120
|
+
log.debug('user', `Processing user ${userId}`)
|
|
121
|
+
```
|
|
122
|
+
|
|
123
|
+
#### Multiple Related Logs
|
|
124
|
+
|
|
125
|
+
```typescript
|
|
126
|
+
// ❌ Before
|
|
127
|
+
console.log('Starting checkout')
|
|
128
|
+
console.log('User:', user.id)
|
|
129
|
+
console.log('Cart items:', cart.items.length)
|
|
130
|
+
console.log('Total:', cart.total)
|
|
131
|
+
|
|
132
|
+
// ✅ After
|
|
133
|
+
log.info({
|
|
134
|
+
action: 'checkout',
|
|
135
|
+
user: { id: user.id },
|
|
136
|
+
cart: { items: cart.items.length, total: cart.total },
|
|
137
|
+
})
|
|
138
|
+
```
|
|
139
|
+
|
|
140
|
+
#### Request Lifecycle Logs
|
|
141
|
+
|
|
142
|
+
```typescript
|
|
143
|
+
// server/api/process.post.ts
|
|
144
|
+
|
|
145
|
+
// ❌ Before
|
|
146
|
+
export default defineEventHandler(async (event) => {
|
|
147
|
+
console.log('Request started')
|
|
148
|
+
const user = await getUser(event)
|
|
149
|
+
console.log('User loaded')
|
|
150
|
+
const result = await processData(user)
|
|
151
|
+
console.log('Processing complete')
|
|
152
|
+
return result
|
|
153
|
+
})
|
|
154
|
+
|
|
155
|
+
// ✅ After (Nuxt - auto-imported, no import needed)
|
|
156
|
+
// For Nitro v3: import { useLogger } from 'evlog/nitro/v3'
|
|
157
|
+
// For Nitro v2: import { useLogger } from 'evlog/nitro'
|
|
158
|
+
|
|
159
|
+
export default defineEventHandler(async (event) => {
|
|
160
|
+
const log = useLogger(event)
|
|
161
|
+
|
|
162
|
+
const user = await getUser(event)
|
|
163
|
+
log.set({ user: { id: user.id } })
|
|
164
|
+
|
|
165
|
+
const result = await processData(user)
|
|
166
|
+
log.set({ result: { id: result.id } })
|
|
167
|
+
|
|
168
|
+
return result
|
|
169
|
+
// emit() called automatically
|
|
170
|
+
})
|
|
171
|
+
```
|
|
172
|
+
|
|
173
|
+
### Error Transformations
|
|
174
|
+
|
|
175
|
+
#### Generic Error
|
|
176
|
+
|
|
177
|
+
```typescript
|
|
178
|
+
// ❌ Before
|
|
179
|
+
throw new Error('Failed to create user')
|
|
180
|
+
|
|
181
|
+
// ✅ After
|
|
182
|
+
throw createError({
|
|
183
|
+
message: 'Failed to create user',
|
|
184
|
+
why: 'Email address already registered',
|
|
185
|
+
fix: 'Use a different email or log in to existing account',
|
|
186
|
+
link: 'https://your-app.com/docs/registration',
|
|
187
|
+
})
|
|
188
|
+
```
|
|
189
|
+
|
|
190
|
+
#### Wrapped Error Without Context
|
|
191
|
+
|
|
192
|
+
```typescript
|
|
193
|
+
// ❌ Before
|
|
194
|
+
try {
|
|
195
|
+
await externalApi.call()
|
|
196
|
+
} catch (error) {
|
|
197
|
+
throw new Error('API call failed')
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
// ✅ After
|
|
201
|
+
try {
|
|
202
|
+
await externalApi.call()
|
|
203
|
+
} catch (error) {
|
|
204
|
+
throw createError({
|
|
205
|
+
message: 'External API call failed',
|
|
206
|
+
why: `API returned: ${error.message}`,
|
|
207
|
+
fix: 'Check API credentials and try again',
|
|
208
|
+
link: 'https://api-docs.example.com/errors',
|
|
209
|
+
cause: error,
|
|
210
|
+
})
|
|
211
|
+
}
|
|
212
|
+
```
|
|
213
|
+
|
|
214
|
+
#### Log-and-Throw Anti-pattern
|
|
215
|
+
|
|
216
|
+
```typescript
|
|
217
|
+
// ❌ Before
|
|
218
|
+
try {
|
|
219
|
+
await riskyOperation()
|
|
220
|
+
} catch (error) {
|
|
221
|
+
console.error('Operation failed:', error)
|
|
222
|
+
throw error
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
// ✅ After
|
|
226
|
+
try {
|
|
227
|
+
await riskyOperation()
|
|
228
|
+
} catch (error) {
|
|
229
|
+
log.error(error, { step: 'riskyOperation' })
|
|
230
|
+
throw createError({
|
|
231
|
+
message: 'Operation failed',
|
|
232
|
+
why: error.message,
|
|
233
|
+
fix: 'Check input and retry',
|
|
234
|
+
cause: error,
|
|
235
|
+
})
|
|
236
|
+
}
|
|
237
|
+
```
|
|
238
|
+
|
|
239
|
+
### Request Handler Transformations
|
|
240
|
+
|
|
241
|
+
#### No Logging
|
|
242
|
+
|
|
243
|
+
```typescript
|
|
244
|
+
// server/api/orders.post.ts
|
|
245
|
+
|
|
246
|
+
// ❌ Before
|
|
247
|
+
export default defineEventHandler(async (event) => {
|
|
248
|
+
const body = await readBody(event)
|
|
249
|
+
const result = await processOrder(body)
|
|
250
|
+
return result
|
|
251
|
+
})
|
|
252
|
+
|
|
253
|
+
// ✅ After (Nuxt - auto-imported, no import needed)
|
|
254
|
+
// For Nitro v3: import { useLogger } from 'evlog/nitro/v3'
|
|
255
|
+
// For Nitro v2: import { useLogger } from 'evlog/nitro'
|
|
256
|
+
import { createError } from 'evlog'
|
|
257
|
+
|
|
258
|
+
export default defineEventHandler(async (event) => {
|
|
259
|
+
const log = useLogger(event)
|
|
260
|
+
|
|
261
|
+
const body = await readBody(event)
|
|
262
|
+
log.set({ order: { items: body.items?.length } })
|
|
263
|
+
|
|
264
|
+
try {
|
|
265
|
+
const result = await processOrder(body)
|
|
266
|
+
log.set({ result: { orderId: result.id, status: result.status } })
|
|
267
|
+
return result
|
|
268
|
+
} catch (error) {
|
|
269
|
+
log.error(error, { step: 'processOrder' })
|
|
270
|
+
throw createError({
|
|
271
|
+
message: 'Order processing failed',
|
|
272
|
+
why: error.message,
|
|
273
|
+
fix: 'Check the order data and try again',
|
|
274
|
+
})
|
|
275
|
+
}
|
|
276
|
+
// emit() called automatically
|
|
277
|
+
})
|
|
278
|
+
```
|
|
279
|
+
|
|
280
|
+
## Review Checklist Summary
|
|
281
|
+
|
|
282
|
+
### Logging
|
|
283
|
+
|
|
284
|
+
- [ ] No raw `console.log` statements in production code
|
|
285
|
+
- [ ] Request handlers use `useLogger(event)` (Nuxt/Nitro) or `createRequestLogger()` (standalone)
|
|
286
|
+
- [ ] Context is accumulated with `log.set()` throughout the request
|
|
287
|
+
- [ ] `emit()` is automatic with `useLogger()`, manual with `createRequestLogger()`
|
|
288
|
+
- [ ] Wide events include: user, business context, outcome
|
|
289
|
+
|
|
290
|
+
### Errors
|
|
291
|
+
|
|
292
|
+
- [ ] All errors use `createError()` instead of `new Error()` (import from `evlog`)
|
|
293
|
+
- [ ] Every error has a clear `message` and appropriate `status` code
|
|
294
|
+
- [ ] Complex errors include `why` explaining root cause
|
|
295
|
+
- [ ] Fixable errors include `fix` with actionable steps
|
|
296
|
+
- [ ] Documented errors include `link` to docs
|
|
297
|
+
- [ ] Wrapped errors preserve `cause`
|
|
298
|
+
- [ ] Support-only or sensitive diagnostics use `internal`, not `message` / `why` / `fix`
|
|
299
|
+
|
|
300
|
+
### Frontend Error Handling
|
|
301
|
+
|
|
302
|
+
- [ ] API errors are caught and displayed with full context (message, why, fix)
|
|
303
|
+
- [ ] Toasts or error components use the structured data from `error.data.data`
|
|
304
|
+
- [ ] Links to documentation are actionable (buttons/links in toasts)
|
|
305
|
+
|
|
306
|
+
### Context
|
|
307
|
+
|
|
308
|
+
- [ ] User context includes: id, plan/subscription, relevant business data
|
|
309
|
+
- [ ] Request context includes: method, path, requestId
|
|
310
|
+
- [ ] Business context is domain-specific and useful for debugging
|
|
311
|
+
- [ ] No sensitive data in logs (passwords, tokens, full card numbers)
|
|
312
|
+
|
|
313
|
+
## Anti-Pattern Summary
|
|
314
|
+
|
|
315
|
+
| Anti-Pattern | Fix |
|
|
316
|
+
| -------------------------------------- | --------------------------------------------------------------------------- |
|
|
317
|
+
| Multiple `console.log` in one function | Single wide event with `useLogger(event).set()` |
|
|
318
|
+
| `throw new Error('...')` | `throw createError({ message, status, why, fix })` |
|
|
319
|
+
| `console.error(e); throw e` | `log.error(e); throw createError(...)` |
|
|
320
|
+
| No logging in request handlers | Add `useLogger(event)` (Nuxt/Nitro) or `createRequestLogger()` (standalone) |
|
|
321
|
+
| Flat log data | Grouped objects: `{ user: {...}, cart: {...} }` |
|
|
322
|
+
| Abbreviated field names | Descriptive names: `userId` not `uid` |
|
|
323
|
+
|
|
324
|
+
## Suggested Review Comments
|
|
325
|
+
|
|
326
|
+
Use these when leaving review feedback:
|
|
327
|
+
|
|
328
|
+
### Console.log Found
|
|
329
|
+
|
|
330
|
+
> Consider using evlog's wide event pattern here. Instead of multiple console.log statements, use `useLogger(event)` to accumulate context and emit a single comprehensive event.
|
|
331
|
+
|
|
332
|
+
### Generic Error
|
|
333
|
+
|
|
334
|
+
> This error would benefit from evlog's structured error pattern. Consider using `import { createError } from 'evlog'` and `createError({ message, status, why, fix })` to provide more debugging context.
|
|
335
|
+
|
|
336
|
+
### Missing Request Context
|
|
337
|
+
|
|
338
|
+
> This handler would benefit from request-scoped logging. Add `useLogger(event)` at the start to capture context throughout the request lifecycle.
|
|
339
|
+
|
|
340
|
+
### Good Logging (Positive Feedback)
|
|
341
|
+
|
|
342
|
+
> Nice use of wide events here! The context is well-structured and will be very useful for debugging.
|
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
# Drain Pipeline Reference
|
|
2
|
+
|
|
3
|
+
The drain pipeline wraps any adapter to add batching, retry with backoff, and buffer overflow protection. Use it in production to reduce network overhead and handle transient failures.
|
|
4
|
+
|
|
5
|
+
## When to Recommend
|
|
6
|
+
|
|
7
|
+
- The user has a drain adapter (Axiom, OTLP, custom) and is deploying to production
|
|
8
|
+
- High-throughput scenarios where one HTTP request per event is wasteful
|
|
9
|
+
- The user needs retry logic for unreliable backends
|
|
10
|
+
- The user is implementing batching manually with `setInterval` and arrays
|
|
11
|
+
|
|
12
|
+
## Basic Setup
|
|
13
|
+
|
|
14
|
+
```typescript
|
|
15
|
+
// server/plugins/evlog-drain.ts
|
|
16
|
+
import type { DrainContext } from 'evlog'
|
|
17
|
+
import { createDrainPipeline } from 'evlog/pipeline'
|
|
18
|
+
import { createAxiomDrain } from 'evlog/axiom'
|
|
19
|
+
|
|
20
|
+
export default defineNitroPlugin((nitroApp) => {
|
|
21
|
+
const pipeline = createDrainPipeline<DrainContext>()
|
|
22
|
+
const drain = pipeline(createAxiomDrain())
|
|
23
|
+
|
|
24
|
+
nitroApp.hooks.hook('evlog:drain', drain)
|
|
25
|
+
nitroApp.hooks.hook('close', () => drain.flush())
|
|
26
|
+
})
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
**Important:** Always call `drain.flush()` on server `close` hook. Without it, buffered events are lost when the process exits.
|
|
30
|
+
|
|
31
|
+
## Full Configuration
|
|
32
|
+
|
|
33
|
+
```typescript
|
|
34
|
+
const pipeline = createDrainPipeline<DrainContext>({
|
|
35
|
+
batch: {
|
|
36
|
+
size: 50, // Max events per batch (default: 50)
|
|
37
|
+
intervalMs: 5000, // Max wait before flushing partial batch (default: 5000)
|
|
38
|
+
},
|
|
39
|
+
retry: {
|
|
40
|
+
maxAttempts: 3, // Total attempts including first (default: 3)
|
|
41
|
+
backoff: 'exponential', // 'exponential' | 'linear' | 'fixed' (default: 'exponential')
|
|
42
|
+
initialDelayMs: 1000, // Base delay for first retry (default: 1000)
|
|
43
|
+
maxDelayMs: 30000, // Upper bound for any retry delay (default: 30000)
|
|
44
|
+
},
|
|
45
|
+
maxBufferSize: 1000, // Max buffered events; oldest dropped on overflow (default: 1000)
|
|
46
|
+
onDropped: (events, error) => {
|
|
47
|
+
// Called when events are dropped (overflow or retry exhaustion)
|
|
48
|
+
console.error(`[evlog] Dropped ${events.length} events:`, error?.message)
|
|
49
|
+
},
|
|
50
|
+
})
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
## How It Works
|
|
54
|
+
|
|
55
|
+
1. `drain(ctx)` pushes a single event into the buffer
|
|
56
|
+
2. When `buffer.length >= batch.size`, the batch is flushed immediately
|
|
57
|
+
3. If the batch isn't full, a timer starts; after `intervalMs`, whatever is buffered gets flushed
|
|
58
|
+
4. On flush, the drain function receives `T[]` (always an array)
|
|
59
|
+
5. Adapter drains built with `defineDrain` / `defineHttpDrain` are unwrapped to their throwing `raw` variant, which defaults to one HTTP attempt per pipeline attempt: the pipeline owns retries, unless `retries` is explicitly configured on the adapter, which then still applies inside each pipeline attempt
|
|
60
|
+
6. If the drain throws, the batch is retried with the configured backoff
|
|
61
|
+
7. After `maxAttempts` failures, `onDropped` is called and the batch is discarded (logged when no `onDropped` is configured)
|
|
62
|
+
8. If the buffer exceeds `maxBufferSize`, the oldest event is dropped and `onDropped` is called
|
|
63
|
+
|
|
64
|
+
## Backoff Strategies
|
|
65
|
+
|
|
66
|
+
| Strategy | Delay Pattern | Best For |
|
|
67
|
+
| ------------- | ----------------- | ------------------------------------------------- |
|
|
68
|
+
| `exponential` | 1s, 2s, 4s, 8s... | Default. Transient failures needing recovery time |
|
|
69
|
+
| `linear` | 1s, 2s, 3s, 4s... | Predictable delay growth |
|
|
70
|
+
| `fixed` | 1s, 1s, 1s, 1s... | Rate-limited APIs with known cooldown |
|
|
71
|
+
|
|
72
|
+
## Returned Drain Function API
|
|
73
|
+
|
|
74
|
+
```typescript
|
|
75
|
+
const drain = pipeline(myDrainFn)
|
|
76
|
+
|
|
77
|
+
drain(ctx) // Push a single event (synchronous, non-blocking)
|
|
78
|
+
await drain.flush() // Force-flush all buffered events
|
|
79
|
+
await drain.settled() // Resolves once everything buffered is delivered or dropped, without forcing a flush
|
|
80
|
+
drain.pending // Number of events currently buffered (readonly)
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
## Serverless
|
|
84
|
+
|
|
85
|
+
`drain(ctx)` returns after buffering, so delivery must outlive the response. When the pipeline is passed as the `drain` option of a framework integration, the shared middleware registers `drain.settled()` with the runtime's `waitUntil` (Next `after()`, Workers `ctx.waitUntil`) automatically: the instance stays alive until the batch is delivered or dropped. Next.js global drains configured through `createInstrumentation()` start inside `after()` and await `drain.settled()` after enqueueing. `batch.intervalMs` bounds when the first delivery attempt starts; retry backoff can extend the lifetime past it. Nitro's `evlog:drain` hook path can't do this for you; on Cloudflare register `drain.settled()` with the execution context's `waitUntil` where the hook is wired.
|
|
86
|
+
|
|
87
|
+
## Common Patterns
|
|
88
|
+
|
|
89
|
+
### With multiple adapters
|
|
90
|
+
|
|
91
|
+
```typescript
|
|
92
|
+
const axiom = createAxiomDrain()
|
|
93
|
+
const otlp = createOTLPDrain()
|
|
94
|
+
|
|
95
|
+
const pipeline = createDrainPipeline<DrainContext>()
|
|
96
|
+
const drain = pipeline(async (batch) => {
|
|
97
|
+
await Promise.allSettled([axiom(batch), otlp(batch)])
|
|
98
|
+
})
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
### Custom drain function
|
|
102
|
+
|
|
103
|
+
```typescript
|
|
104
|
+
const pipeline = createDrainPipeline<DrainContext>({ batch: { size: 100 } })
|
|
105
|
+
const drain = pipeline(async (batch) => {
|
|
106
|
+
await fetch('https://your-service.com/logs', {
|
|
107
|
+
method: 'POST',
|
|
108
|
+
headers: { 'Content-Type': 'application/json' },
|
|
109
|
+
body: JSON.stringify(batch.map((ctx) => ctx.event)),
|
|
110
|
+
})
|
|
111
|
+
})
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
### Low-traffic with longer interval
|
|
115
|
+
|
|
116
|
+
```typescript
|
|
117
|
+
const pipeline = createDrainPipeline<DrainContext>({
|
|
118
|
+
batch: { size: 10, intervalMs: 30000 }, // Flush every 30s or 10 events
|
|
119
|
+
})
|
|
120
|
+
```
|
|
121
|
+
|
|
122
|
+
## Anti-Patterns
|
|
123
|
+
|
|
124
|
+
### Manual batching with setInterval
|
|
125
|
+
|
|
126
|
+
```typescript
|
|
127
|
+
// ❌ No retry, no overflow protection, no flush on shutdown
|
|
128
|
+
const batch: WideEvent[] = []
|
|
129
|
+
setInterval(() => {
|
|
130
|
+
if (batch.length > 0) fetch(...)
|
|
131
|
+
}, 5000)
|
|
132
|
+
```
|
|
133
|
+
|
|
134
|
+
**Transform to:**
|
|
135
|
+
|
|
136
|
+
```typescript
|
|
137
|
+
// ✅ Use the pipeline
|
|
138
|
+
const pipeline = createDrainPipeline<DrainContext>()
|
|
139
|
+
const drain = pipeline(async (batch) => { await fetch(...) })
|
|
140
|
+
nitroApp.hooks.hook('close', () => drain.flush())
|
|
141
|
+
```
|
|
142
|
+
|
|
143
|
+
### Missing flush on shutdown
|
|
144
|
+
|
|
145
|
+
```typescript
|
|
146
|
+
// ❌ Buffered events lost on process exit
|
|
147
|
+
nitroApp.hooks.hook('evlog:drain', drain)
|
|
148
|
+
```
|
|
149
|
+
|
|
150
|
+
**Fix:**
|
|
151
|
+
|
|
152
|
+
```typescript
|
|
153
|
+
// ✅ Always flush on close
|
|
154
|
+
nitroApp.hooks.hook('evlog:drain', drain)
|
|
155
|
+
nitroApp.hooks.hook('close', () => drain.flush())
|
|
156
|
+
```
|
|
157
|
+
|
|
158
|
+
## Review Checklist
|
|
159
|
+
|
|
160
|
+
- [ ] Pipeline wraps the adapter for production use
|
|
161
|
+
- [ ] `drain.flush()` called on server `close` hook (long-lived servers)
|
|
162
|
+
- [ ] On serverless, the pipeline is passed as the integration's `drain` option (settled() registration is automatic); Nitro-on-Cloudflare wires `drain.settled()` into `waitUntil` manually
|
|
163
|
+
- [ ] `onDropped` callback logs or reports dropped events
|
|
164
|
+
- [ ] Retries are owned by one layer: no explicit `retries` on the adapter config when the pipeline wraps it
|
|
165
|
+
- [ ] Batch size and interval are appropriate for the traffic volume
|
|
166
|
+
- [ ] `maxBufferSize` is set to prevent memory leaks under load
|