@logtape/koa 1.3.0-dev.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.
@@ -0,0 +1,727 @@
1
+ import { suite } from "@alinea/suite";
2
+ import { assert, assertEquals, assertExists } from "@std/assert";
3
+ import { configure, type LogRecord, reset } from "@logtape/logtape";
4
+ import { type KoaContext, koaLogger, type KoaMiddleware } from "./mod.ts";
5
+
6
+ const test = suite(import.meta);
7
+
8
+ // Test fixture: Collect log records, filtering out internal LogTape meta logs
9
+ function createTestSink(): {
10
+ sink: (record: LogRecord) => void;
11
+ logs: LogRecord[];
12
+ } {
13
+ const logs: LogRecord[] = [];
14
+ return {
15
+ sink: (record: LogRecord) => {
16
+ if (record.category[0] !== "logtape") {
17
+ logs.push(record);
18
+ }
19
+ },
20
+ logs,
21
+ };
22
+ }
23
+
24
+ // Setup helper
25
+ async function setupLogtape(): Promise<{
26
+ logs: LogRecord[];
27
+ cleanup: () => Promise<void>;
28
+ }> {
29
+ const { sink, logs } = createTestSink();
30
+ await configure({
31
+ sinks: { test: sink },
32
+ loggers: [{ category: [], sinks: ["test"] }],
33
+ });
34
+ return { logs, cleanup: () => reset() };
35
+ }
36
+
37
+ // Mock Koa context
38
+ function createMockContext(overrides: Partial<KoaContext> = {}): KoaContext {
39
+ return {
40
+ method: "GET",
41
+ url: "/test",
42
+ path: "/test",
43
+ status: 200,
44
+ ip: "127.0.0.1",
45
+ response: {
46
+ length: undefined,
47
+ },
48
+ get: (field: string) => {
49
+ const headers: Record<string, string> = {
50
+ "user-agent": "test-agent/1.0",
51
+ "referer": "http://example.com",
52
+ "referrer": "http://example.com",
53
+ };
54
+ return headers[field.toLowerCase()] ?? "";
55
+ },
56
+ ...overrides,
57
+ };
58
+ }
59
+
60
+ // Helper to run middleware
61
+ async function runMiddleware(
62
+ middleware: KoaMiddleware,
63
+ ctx: KoaContext,
64
+ next: () => Promise<void> = async () => {},
65
+ ): Promise<void> {
66
+ await middleware(ctx, next);
67
+ }
68
+
69
+ // ============================================
70
+ // Basic Middleware Creation Tests
71
+ // ============================================
72
+
73
+ test("koaLogger(): creates a middleware function", async () => {
74
+ const { cleanup } = await setupLogtape();
75
+ try {
76
+ const middleware = koaLogger();
77
+ assertEquals(typeof middleware, "function");
78
+ } finally {
79
+ await cleanup();
80
+ }
81
+ });
82
+
83
+ test("koaLogger(): logs request after response", async () => {
84
+ const { logs, cleanup } = await setupLogtape();
85
+ try {
86
+ const middleware = koaLogger();
87
+ const ctx = createMockContext();
88
+
89
+ await runMiddleware(middleware, ctx);
90
+
91
+ assertEquals(logs.length, 1);
92
+ } finally {
93
+ await cleanup();
94
+ }
95
+ });
96
+
97
+ // ============================================
98
+ // Category Configuration Tests
99
+ // ============================================
100
+
101
+ test("koaLogger(): uses default category ['koa']", async () => {
102
+ const { logs, cleanup } = await setupLogtape();
103
+ try {
104
+ const middleware = koaLogger();
105
+ const ctx = createMockContext();
106
+
107
+ await runMiddleware(middleware, ctx);
108
+
109
+ assertEquals(logs.length, 1);
110
+ assertEquals(logs[0].category, ["koa"]);
111
+ } finally {
112
+ await cleanup();
113
+ }
114
+ });
115
+
116
+ test("koaLogger(): uses custom category array", async () => {
117
+ const { logs, cleanup } = await setupLogtape();
118
+ try {
119
+ const middleware = koaLogger({ category: ["myapp", "http"] });
120
+ const ctx = createMockContext();
121
+
122
+ await runMiddleware(middleware, ctx);
123
+
124
+ assertEquals(logs.length, 1);
125
+ assertEquals(logs[0].category, ["myapp", "http"]);
126
+ } finally {
127
+ await cleanup();
128
+ }
129
+ });
130
+
131
+ test("koaLogger(): accepts string category", async () => {
132
+ const { logs, cleanup } = await setupLogtape();
133
+ try {
134
+ const middleware = koaLogger({ category: "myapp" });
135
+ const ctx = createMockContext();
136
+
137
+ await runMiddleware(middleware, ctx);
138
+
139
+ assertEquals(logs.length, 1);
140
+ assertEquals(logs[0].category, ["myapp"]);
141
+ } finally {
142
+ await cleanup();
143
+ }
144
+ });
145
+
146
+ // ============================================
147
+ // Log Level Tests
148
+ // ============================================
149
+
150
+ test("koaLogger(): uses default log level 'info'", async () => {
151
+ const { logs, cleanup } = await setupLogtape();
152
+ try {
153
+ const middleware = koaLogger();
154
+ const ctx = createMockContext();
155
+
156
+ await runMiddleware(middleware, ctx);
157
+
158
+ assertEquals(logs.length, 1);
159
+ assertEquals(logs[0].level, "info");
160
+ } finally {
161
+ await cleanup();
162
+ }
163
+ });
164
+
165
+ test("koaLogger(): uses custom log level 'debug'", async () => {
166
+ const { logs, cleanup } = await setupLogtape();
167
+ try {
168
+ const middleware = koaLogger({ level: "debug" });
169
+ const ctx = createMockContext();
170
+
171
+ await runMiddleware(middleware, ctx);
172
+
173
+ assertEquals(logs.length, 1);
174
+ assertEquals(logs[0].level, "debug");
175
+ } finally {
176
+ await cleanup();
177
+ }
178
+ });
179
+
180
+ test("koaLogger(): uses custom log level 'warning'", async () => {
181
+ const { logs, cleanup } = await setupLogtape();
182
+ try {
183
+ const middleware = koaLogger({ level: "warning" });
184
+ const ctx = createMockContext();
185
+
186
+ await runMiddleware(middleware, ctx);
187
+
188
+ assertEquals(logs.length, 1);
189
+ assertEquals(logs[0].level, "warning");
190
+ } finally {
191
+ await cleanup();
192
+ }
193
+ });
194
+
195
+ // ============================================
196
+ // Format Tests - Combined (default)
197
+ // ============================================
198
+
199
+ test("koaLogger(): combined format logs structured properties", async () => {
200
+ const { logs, cleanup } = await setupLogtape();
201
+ try {
202
+ const middleware = koaLogger({ format: "combined" });
203
+ const ctx = createMockContext({
204
+ response: { length: 123 },
205
+ });
206
+
207
+ await runMiddleware(middleware, ctx);
208
+
209
+ assertEquals(logs.length, 1);
210
+ const props = logs[0].properties;
211
+ assertEquals(props.method, "GET");
212
+ assertEquals(props.url, "/test");
213
+ assertEquals(props.path, "/test");
214
+ assertEquals(props.status, 200);
215
+ assertExists(props.responseTime);
216
+ assertEquals(props.contentLength, 123);
217
+ assertEquals(props.remoteAddr, "127.0.0.1");
218
+ assertEquals(props.userAgent, "test-agent/1.0");
219
+ assertEquals(props.referrer, "http://example.com");
220
+ } finally {
221
+ await cleanup();
222
+ }
223
+ });
224
+
225
+ // ============================================
226
+ // Format Tests - Common
227
+ // ============================================
228
+
229
+ test("koaLogger(): common format excludes referrer and userAgent", async () => {
230
+ const { logs, cleanup } = await setupLogtape();
231
+ try {
232
+ const middleware = koaLogger({ format: "common" });
233
+ const ctx = createMockContext();
234
+
235
+ await runMiddleware(middleware, ctx);
236
+
237
+ assertEquals(logs.length, 1);
238
+ const props = logs[0].properties;
239
+ assertEquals(props.method, "GET");
240
+ assertEquals(props.path, "/test");
241
+ assertEquals(props.status, 200);
242
+ assertEquals(props.referrer, undefined);
243
+ assertEquals(props.userAgent, undefined);
244
+ } finally {
245
+ await cleanup();
246
+ }
247
+ });
248
+
249
+ // ============================================
250
+ // Format Tests - Dev
251
+ // ============================================
252
+
253
+ test("koaLogger(): dev format returns string message", async () => {
254
+ const { logs, cleanup } = await setupLogtape();
255
+ try {
256
+ const middleware = koaLogger({ format: "dev" });
257
+ const ctx = createMockContext({
258
+ method: "POST",
259
+ path: "/api/users",
260
+ status: 201,
261
+ response: { length: 456 },
262
+ });
263
+
264
+ await runMiddleware(middleware, ctx);
265
+
266
+ assertEquals(logs.length, 1);
267
+ const msg = logs[0].rawMessage;
268
+ assert(msg.includes("POST"));
269
+ assert(msg.includes("/api/users"));
270
+ assert(msg.includes("201"));
271
+ assert(msg.includes("ms"));
272
+ assert(msg.includes("456"));
273
+ } finally {
274
+ await cleanup();
275
+ }
276
+ });
277
+
278
+ // ============================================
279
+ // Format Tests - Short
280
+ // ============================================
281
+
282
+ test("koaLogger(): short format includes remote addr", async () => {
283
+ const { logs, cleanup } = await setupLogtape();
284
+ try {
285
+ const middleware = koaLogger({ format: "short" });
286
+ const ctx = createMockContext({
287
+ ip: "192.168.1.1",
288
+ });
289
+
290
+ await runMiddleware(middleware, ctx);
291
+
292
+ assertEquals(logs.length, 1);
293
+ const msg = logs[0].rawMessage;
294
+ assert(msg.includes("192.168.1.1"));
295
+ assert(msg.includes("GET"));
296
+ assert(msg.includes("/test"));
297
+ } finally {
298
+ await cleanup();
299
+ }
300
+ });
301
+
302
+ // ============================================
303
+ // Format Tests - Tiny
304
+ // ============================================
305
+
306
+ test("koaLogger(): tiny format is minimal", async () => {
307
+ const { logs, cleanup } = await setupLogtape();
308
+ try {
309
+ const middleware = koaLogger({ format: "tiny" });
310
+ const ctx = createMockContext({ status: 404 });
311
+
312
+ await runMiddleware(middleware, ctx);
313
+
314
+ assertEquals(logs.length, 1);
315
+ const msg = logs[0].rawMessage;
316
+ assert(msg.includes("GET"));
317
+ assert(msg.includes("/test"));
318
+ assert(msg.includes("404"));
319
+ assert(msg.includes("ms"));
320
+ // Tiny format should NOT include remote addr
321
+ assert(!msg.includes("127.0.0.1"));
322
+ } finally {
323
+ await cleanup();
324
+ }
325
+ });
326
+
327
+ // ============================================
328
+ // Custom Format Function Tests
329
+ // ============================================
330
+
331
+ test("koaLogger(): custom format returning string", async () => {
332
+ const { logs, cleanup } = await setupLogtape();
333
+ try {
334
+ const middleware = koaLogger({
335
+ format: (ctx: KoaContext, _responseTime: number) =>
336
+ `Custom: ${ctx.method} ${ctx.status}`,
337
+ });
338
+ const ctx = createMockContext({ method: "DELETE", status: 204 });
339
+
340
+ await runMiddleware(middleware, ctx);
341
+
342
+ assertEquals(logs.length, 1);
343
+ assertEquals(logs[0].rawMessage, "Custom: DELETE 204");
344
+ } finally {
345
+ await cleanup();
346
+ }
347
+ });
348
+
349
+ test("koaLogger(): custom format returning object", async () => {
350
+ const { logs, cleanup } = await setupLogtape();
351
+ try {
352
+ const middleware = koaLogger({
353
+ format: (ctx: KoaContext, responseTime: number) => ({
354
+ customMethod: ctx.method,
355
+ customStatus: ctx.status,
356
+ customDuration: responseTime,
357
+ }),
358
+ });
359
+ const ctx = createMockContext({ method: "PATCH", status: 202 });
360
+
361
+ await runMiddleware(middleware, ctx);
362
+
363
+ assertEquals(logs.length, 1);
364
+ assertEquals(logs[0].properties.customMethod, "PATCH");
365
+ assertEquals(logs[0].properties.customStatus, 202);
366
+ assertExists(logs[0].properties.customDuration);
367
+ } finally {
368
+ await cleanup();
369
+ }
370
+ });
371
+
372
+ // ============================================
373
+ // Skip Function Tests
374
+ // ============================================
375
+
376
+ test("koaLogger(): skip function prevents logging when returns true", async () => {
377
+ const { logs, cleanup } = await setupLogtape();
378
+ try {
379
+ const middleware = koaLogger({
380
+ skip: () => true,
381
+ });
382
+ const ctx = createMockContext();
383
+
384
+ await runMiddleware(middleware, ctx);
385
+
386
+ assertEquals(logs.length, 0);
387
+ } finally {
388
+ await cleanup();
389
+ }
390
+ });
391
+
392
+ test("koaLogger(): skip function allows logging when returns false", async () => {
393
+ const { logs, cleanup } = await setupLogtape();
394
+ try {
395
+ const middleware = koaLogger({
396
+ skip: () => false,
397
+ });
398
+ const ctx = createMockContext();
399
+
400
+ await runMiddleware(middleware, ctx);
401
+
402
+ assertEquals(logs.length, 1);
403
+ } finally {
404
+ await cleanup();
405
+ }
406
+ });
407
+
408
+ test("koaLogger(): skip function receives context", async () => {
409
+ const { logs, cleanup } = await setupLogtape();
410
+ try {
411
+ const middleware = koaLogger({
412
+ skip: (ctx: KoaContext) => ctx.path === "/health",
413
+ });
414
+
415
+ // Health endpoint should be skipped
416
+ const healthCtx = createMockContext({ path: "/health" });
417
+ await runMiddleware(middleware, healthCtx);
418
+ assertEquals(logs.length, 0);
419
+
420
+ // Other endpoints should be logged
421
+ const testCtx = createMockContext({ path: "/test" });
422
+ await runMiddleware(middleware, testCtx);
423
+ assertEquals(logs.length, 1);
424
+ } finally {
425
+ await cleanup();
426
+ }
427
+ });
428
+
429
+ // ============================================
430
+ // logRequest (Immediate) Mode Tests
431
+ // ============================================
432
+
433
+ test("koaLogger(): logRequest mode logs at request start", async () => {
434
+ const { logs, cleanup } = await setupLogtape();
435
+ try {
436
+ const middleware = koaLogger({ logRequest: true });
437
+ const ctx = createMockContext();
438
+
439
+ await runMiddleware(middleware, ctx);
440
+
441
+ assertEquals(logs.length, 1);
442
+ assertEquals(logs[0].properties.responseTime, 0); // Zero because it's immediate
443
+ } finally {
444
+ await cleanup();
445
+ }
446
+ });
447
+
448
+ test("koaLogger(): non-logRequest mode logs after response", async () => {
449
+ const { logs, cleanup } = await setupLogtape();
450
+ try {
451
+ const middleware = koaLogger({ logRequest: false });
452
+ const ctx = createMockContext();
453
+
454
+ await runMiddleware(middleware, ctx, async () => {
455
+ // Small delay to ensure non-zero response time
456
+ await new Promise((resolve) => setTimeout(resolve, 5));
457
+ });
458
+
459
+ assertEquals(logs.length, 1);
460
+ assert((logs[0].properties.responseTime as number) >= 0);
461
+ } finally {
462
+ await cleanup();
463
+ }
464
+ });
465
+
466
+ // ============================================
467
+ // Request Property Tests
468
+ // ============================================
469
+
470
+ test("koaLogger(): logs correct method", async () => {
471
+ const { logs, cleanup } = await setupLogtape();
472
+ try {
473
+ const middleware = koaLogger();
474
+
475
+ const methods = ["GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"];
476
+ for (const method of methods) {
477
+ const ctx = createMockContext({ method });
478
+ await runMiddleware(middleware, ctx);
479
+ }
480
+
481
+ assertEquals(logs.length, methods.length);
482
+ for (let i = 0; i < methods.length; i++) {
483
+ assertEquals(logs[i].properties.method, methods[i]);
484
+ }
485
+ } finally {
486
+ await cleanup();
487
+ }
488
+ });
489
+
490
+ test("koaLogger(): logs path correctly", async () => {
491
+ const { logs, cleanup } = await setupLogtape();
492
+ try {
493
+ const middleware = koaLogger();
494
+ const ctx = createMockContext({ path: "/api/v1/users" });
495
+
496
+ await runMiddleware(middleware, ctx);
497
+
498
+ assertEquals(logs.length, 1);
499
+ assertEquals(logs[0].properties.path, "/api/v1/users");
500
+ } finally {
501
+ await cleanup();
502
+ }
503
+ });
504
+
505
+ test("koaLogger(): logs status code", async () => {
506
+ const { logs, cleanup } = await setupLogtape();
507
+ try {
508
+ const middleware = koaLogger();
509
+
510
+ const statusCodes = [200, 201, 301, 400, 404, 500];
511
+ for (const status of statusCodes) {
512
+ const ctx = createMockContext({ status });
513
+ await runMiddleware(middleware, ctx);
514
+ }
515
+
516
+ assertEquals(logs.length, statusCodes.length);
517
+ for (let i = 0; i < statusCodes.length; i++) {
518
+ assertEquals(logs[i].properties.status, statusCodes[i]);
519
+ }
520
+ } finally {
521
+ await cleanup();
522
+ }
523
+ });
524
+
525
+ test("koaLogger(): logs response time as number", async () => {
526
+ const { logs, cleanup } = await setupLogtape();
527
+ try {
528
+ const middleware = koaLogger();
529
+ const ctx = createMockContext();
530
+
531
+ await runMiddleware(middleware, ctx, async () => {
532
+ // Add small delay to ensure non-zero response time
533
+ await new Promise((resolve) => setTimeout(resolve, 10));
534
+ });
535
+
536
+ assertEquals(logs.length, 1);
537
+ assertEquals(typeof logs[0].properties.responseTime, "number");
538
+ assert((logs[0].properties.responseTime as number) >= 0);
539
+ } finally {
540
+ await cleanup();
541
+ }
542
+ });
543
+
544
+ test("koaLogger(): logs content-length when present", async () => {
545
+ const { logs, cleanup } = await setupLogtape();
546
+ try {
547
+ const middleware = koaLogger();
548
+ const ctx = createMockContext({
549
+ response: { length: 1024 },
550
+ });
551
+
552
+ await runMiddleware(middleware, ctx);
553
+
554
+ assertEquals(logs.length, 1);
555
+ assertEquals(logs[0].properties.contentLength, 1024);
556
+ } finally {
557
+ await cleanup();
558
+ }
559
+ });
560
+
561
+ test("koaLogger(): logs undefined contentLength when not set", async () => {
562
+ const { logs, cleanup } = await setupLogtape();
563
+ try {
564
+ const middleware = koaLogger();
565
+ const ctx = createMockContext({
566
+ response: { length: undefined },
567
+ });
568
+
569
+ await runMiddleware(middleware, ctx);
570
+
571
+ assertEquals(logs.length, 1);
572
+ assertEquals(logs[0].properties.contentLength, undefined);
573
+ } finally {
574
+ await cleanup();
575
+ }
576
+ });
577
+
578
+ test("koaLogger(): logs remote address from ctx.ip", async () => {
579
+ const { logs, cleanup } = await setupLogtape();
580
+ try {
581
+ const middleware = koaLogger();
582
+ const ctx = createMockContext({
583
+ ip: "10.0.0.1",
584
+ });
585
+
586
+ await runMiddleware(middleware, ctx);
587
+
588
+ assertEquals(logs.length, 1);
589
+ assertEquals(logs[0].properties.remoteAddr, "10.0.0.1");
590
+ } finally {
591
+ await cleanup();
592
+ }
593
+ });
594
+
595
+ test("koaLogger(): logs user agent", async () => {
596
+ const { logs, cleanup } = await setupLogtape();
597
+ try {
598
+ const middleware = koaLogger();
599
+ const ctx = createMockContext({
600
+ get: (field: string) => {
601
+ if (field.toLowerCase() === "user-agent") return "TestClient/1.0";
602
+ return "";
603
+ },
604
+ });
605
+
606
+ await runMiddleware(middleware, ctx);
607
+
608
+ assertEquals(logs.length, 1);
609
+ assertEquals(logs[0].properties.userAgent, "TestClient/1.0");
610
+ } finally {
611
+ await cleanup();
612
+ }
613
+ });
614
+
615
+ test("koaLogger(): logs referrer", async () => {
616
+ const { logs, cleanup } = await setupLogtape();
617
+ try {
618
+ const middleware = koaLogger();
619
+ const ctx = createMockContext({
620
+ get: (field: string) => {
621
+ if (field.toLowerCase() === "referer") {
622
+ return "https://example.com/page";
623
+ }
624
+ if (field.toLowerCase() === "referrer") {
625
+ return "https://example.com/page";
626
+ }
627
+ return "";
628
+ },
629
+ });
630
+
631
+ await runMiddleware(middleware, ctx);
632
+
633
+ assertEquals(logs.length, 1);
634
+ assertEquals(logs[0].properties.referrer, "https://example.com/page");
635
+ } finally {
636
+ await cleanup();
637
+ }
638
+ });
639
+
640
+ // ============================================
641
+ // Multiple Requests Tests
642
+ // ============================================
643
+
644
+ test("koaLogger(): handles multiple sequential requests", async () => {
645
+ const { logs, cleanup } = await setupLogtape();
646
+ try {
647
+ const middleware = koaLogger();
648
+
649
+ for (let i = 0; i < 5; i++) {
650
+ const ctx = createMockContext({
651
+ path: `/path/${i}`,
652
+ url: `/path/${i}`,
653
+ status: 200 + i,
654
+ });
655
+ await runMiddleware(middleware, ctx);
656
+ }
657
+
658
+ assertEquals(logs.length, 5);
659
+ for (let i = 0; i < 5; i++) {
660
+ assertEquals(logs[i].properties.path, `/path/${i}`);
661
+ assertEquals(logs[i].properties.status, 200 + i);
662
+ }
663
+ } finally {
664
+ await cleanup();
665
+ }
666
+ });
667
+
668
+ // ============================================
669
+ // Edge Cases
670
+ // ============================================
671
+
672
+ test("koaLogger(): handles missing user-agent", async () => {
673
+ const { logs, cleanup } = await setupLogtape();
674
+ try {
675
+ const middleware = koaLogger();
676
+ const ctx = createMockContext({
677
+ get: () => "",
678
+ });
679
+
680
+ await runMiddleware(middleware, ctx);
681
+
682
+ assertEquals(logs.length, 1);
683
+ assertEquals(logs[0].properties.userAgent, undefined);
684
+ } finally {
685
+ await cleanup();
686
+ }
687
+ });
688
+
689
+ test("koaLogger(): handles missing referrer", async () => {
690
+ const { logs, cleanup } = await setupLogtape();
691
+ try {
692
+ const middleware = koaLogger();
693
+ const ctx = createMockContext({
694
+ get: (field: string) => {
695
+ if (field.toLowerCase() === "user-agent") return "test-agent";
696
+ return "";
697
+ },
698
+ });
699
+
700
+ await runMiddleware(middleware, ctx);
701
+
702
+ assertEquals(logs.length, 1);
703
+ assertEquals(logs[0].properties.referrer, undefined);
704
+ } finally {
705
+ await cleanup();
706
+ }
707
+ });
708
+
709
+ test("koaLogger(): handles query parameters in url", async () => {
710
+ const { logs, cleanup } = await setupLogtape();
711
+ try {
712
+ const middleware = koaLogger();
713
+ const ctx = createMockContext({
714
+ path: "/search",
715
+ url: "/search?q=test&limit=10",
716
+ });
717
+
718
+ await runMiddleware(middleware, ctx);
719
+
720
+ assertEquals(logs.length, 1);
721
+ assertEquals(logs[0].properties.path, "/search");
722
+ assert((logs[0].properties.url as string).includes("q=test"));
723
+ assert((logs[0].properties.url as string).includes("limit=10"));
724
+ } finally {
725
+ await cleanup();
726
+ }
727
+ });