@logtape/express 1.4.0-dev.409 → 1.4.0-dev.413

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 CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@logtape/express",
3
- "version": "1.4.0-dev.409+63c2cd45",
3
+ "version": "1.4.0-dev.413+1097da33",
4
4
  "description": "Express adapter for LogTape logging library",
5
5
  "keywords": [
6
6
  "logging",
@@ -48,9 +48,12 @@
48
48
  "./package.json": "./package.json"
49
49
  },
50
50
  "sideEffects": false,
51
+ "files": [
52
+ "dist/"
53
+ ],
51
54
  "peerDependencies": {
52
55
  "express": "^4.0.0 || ^5.0.0",
53
- "@logtape/logtape": "^1.4.0-dev.409+63c2cd45"
56
+ "@logtape/logtape": "^1.4.0-dev.413+1097da33"
54
57
  },
55
58
  "devDependencies": {
56
59
  "@alinea/suite": "^0.6.3",
package/deno.json DELETED
@@ -1,34 +0,0 @@
1
- {
2
- "name": "@logtape/express",
3
- "version": "1.4.0-dev.409+63c2cd45",
4
- "license": "MIT",
5
- "exports": "./src/mod.ts",
6
- "exclude": [
7
- "coverage/",
8
- "npm/",
9
- "dist/"
10
- ],
11
- "tasks": {
12
- "build": "pnpm build",
13
- "test": "deno test --allow-env --allow-sys --allow-net",
14
- "test:node": {
15
- "dependencies": [
16
- "build"
17
- ],
18
- "command": "node --experimental-transform-types --test"
19
- },
20
- "test:bun": {
21
- "dependencies": [
22
- "build"
23
- ],
24
- "command": "bun test"
25
- },
26
- "test-all": {
27
- "dependencies": [
28
- "test",
29
- "test:node",
30
- "test:bun"
31
- ]
32
- }
33
- }
34
- }
package/src/mod.test.ts DELETED
@@ -1,875 +0,0 @@
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 {
5
- expressLogger,
6
- type ExpressNextFunction,
7
- type ExpressRequest,
8
- type ExpressResponse,
9
- } from "./mod.ts";
10
- import { EventEmitter } from "node:events";
11
-
12
- const test = suite(import.meta);
13
-
14
- // Test fixture: Collect log records, filtering out internal LogTape meta logs
15
- function createTestSink(): {
16
- sink: (record: LogRecord) => void;
17
- logs: LogRecord[];
18
- } {
19
- const logs: LogRecord[] = [];
20
- return {
21
- sink: (record: LogRecord) => {
22
- if (record.category[0] !== "logtape") {
23
- logs.push(record);
24
- }
25
- },
26
- logs,
27
- };
28
- }
29
-
30
- // Setup helper
31
- async function setupLogtape(): Promise<{
32
- logs: LogRecord[];
33
- cleanup: () => Promise<void>;
34
- }> {
35
- const { sink, logs } = createTestSink();
36
- await configure({
37
- sinks: { test: sink },
38
- loggers: [{ category: [], sinks: ["test"] }],
39
- });
40
- return { logs, cleanup: () => reset() };
41
- }
42
-
43
- // Mock Express request
44
- function createMockRequest(
45
- overrides: Partial<ExpressRequest> = {},
46
- ): ExpressRequest {
47
- return {
48
- method: "GET",
49
- url: "/test",
50
- originalUrl: "/test",
51
- httpVersion: "1.1",
52
- ip: "127.0.0.1",
53
- socket: { remoteAddress: "127.0.0.1" },
54
- get: (header: string) => {
55
- const headers: Record<string, string> = {
56
- "user-agent": "test-agent/1.0",
57
- "referrer": "http://example.com",
58
- "referer": "http://example.com",
59
- };
60
- return headers[header.toLowerCase()];
61
- },
62
- ...overrides,
63
- };
64
- }
65
-
66
- // Mock Express response with EventEmitter
67
- function createMockResponse(
68
- overrides: Partial<
69
- ExpressResponse & {
70
- setHeader: (name: string, value: string | number) => void;
71
- }
72
- > = {},
73
- ): ExpressResponse & {
74
- setHeader: (name: string, value: string | number) => void;
75
- } {
76
- const emitter = new EventEmitter();
77
- const headers: Record<string, string | number> = {};
78
-
79
- return {
80
- statusCode: 200,
81
- on: emitter.on.bind(emitter) as ExpressResponse["on"],
82
- getHeader: (name: string) => headers[name.toLowerCase()],
83
- setHeader: (name: string, value: string | number) => {
84
- headers[name.toLowerCase()] = value;
85
- },
86
- _emitter: emitter,
87
- ...overrides,
88
- } as ExpressResponse & {
89
- setHeader: (name: string, value: string | number) => void;
90
- _emitter?: EventEmitter;
91
- };
92
- }
93
-
94
- // Helper to simulate response finish
95
- function finishResponse(res: ExpressResponse): void {
96
- // @ts-ignore - accessing internal emitter for testing
97
- const emitter = (res as { _emitter?: EventEmitter })._emitter;
98
- if (emitter) {
99
- emitter.emit("finish");
100
- }
101
- }
102
-
103
- // ============================================
104
- // Basic Middleware Creation Tests
105
- // ============================================
106
-
107
- test("expressLogger(): creates a middleware function", async () => {
108
- const { cleanup } = await setupLogtape();
109
- try {
110
- const middleware = expressLogger();
111
-
112
- assertEquals(typeof middleware, "function");
113
- assertEquals(middleware.length, 3); // req, res, next
114
- } finally {
115
- await cleanup();
116
- }
117
- });
118
-
119
- test("expressLogger(): calls next() to continue middleware chain", async () => {
120
- const { cleanup } = await setupLogtape();
121
- try {
122
- const middleware = expressLogger();
123
- const req = createMockRequest();
124
- const res = createMockResponse();
125
- let nextCalled = false;
126
- const next: ExpressNextFunction = () => {
127
- nextCalled = true;
128
- };
129
-
130
- middleware(req, res, next);
131
-
132
- assert(nextCalled);
133
- } finally {
134
- await cleanup();
135
- }
136
- });
137
-
138
- // ============================================
139
- // Category Configuration Tests
140
- // ============================================
141
-
142
- test("expressLogger(): uses default category ['express']", async () => {
143
- const { logs, cleanup } = await setupLogtape();
144
- try {
145
- const middleware = expressLogger();
146
- const req = createMockRequest();
147
- const res = createMockResponse();
148
- const next: ExpressNextFunction = () => {};
149
-
150
- middleware(req, res, next);
151
- finishResponse(res);
152
-
153
- assertEquals(logs.length, 1);
154
- assertEquals(logs[0].category, ["express"]);
155
- } finally {
156
- await cleanup();
157
- }
158
- });
159
-
160
- test("expressLogger(): uses custom category array", async () => {
161
- const { logs, cleanup } = await setupLogtape();
162
- try {
163
- const middleware = expressLogger({ category: ["myapp", "http"] });
164
- const req = createMockRequest();
165
- const res = createMockResponse();
166
- const next: ExpressNextFunction = () => {};
167
-
168
- middleware(req, res, next);
169
- finishResponse(res);
170
-
171
- assertEquals(logs.length, 1);
172
- assertEquals(logs[0].category, ["myapp", "http"]);
173
- } finally {
174
- await cleanup();
175
- }
176
- });
177
-
178
- test("expressLogger(): accepts string category", async () => {
179
- const { logs, cleanup } = await setupLogtape();
180
- try {
181
- const middleware = expressLogger({ category: "myapp" });
182
- const req = createMockRequest();
183
- const res = createMockResponse();
184
- const next: ExpressNextFunction = () => {};
185
-
186
- middleware(req, res, next);
187
- finishResponse(res);
188
-
189
- assertEquals(logs.length, 1);
190
- assertEquals(logs[0].category, ["myapp"]);
191
- } finally {
192
- await cleanup();
193
- }
194
- });
195
-
196
- // ============================================
197
- // Log Level Tests
198
- // ============================================
199
-
200
- test("expressLogger(): uses default log level 'info'", async () => {
201
- const { logs, cleanup } = await setupLogtape();
202
- try {
203
- const middleware = expressLogger();
204
- const req = createMockRequest();
205
- const res = createMockResponse();
206
- const next: ExpressNextFunction = () => {};
207
-
208
- middleware(req, res, next);
209
- finishResponse(res);
210
-
211
- assertEquals(logs.length, 1);
212
- assertEquals(logs[0].level, "info");
213
- } finally {
214
- await cleanup();
215
- }
216
- });
217
-
218
- test("expressLogger(): uses custom log level 'debug'", async () => {
219
- const { logs, cleanup } = await setupLogtape();
220
- try {
221
- const middleware = expressLogger({ level: "debug" });
222
- const req = createMockRequest();
223
- const res = createMockResponse();
224
- const next: ExpressNextFunction = () => {};
225
-
226
- middleware(req, res, next);
227
- finishResponse(res);
228
-
229
- assertEquals(logs.length, 1);
230
- assertEquals(logs[0].level, "debug");
231
- } finally {
232
- await cleanup();
233
- }
234
- });
235
-
236
- test("expressLogger(): uses custom log level 'warning'", async () => {
237
- const { logs, cleanup } = await setupLogtape();
238
- try {
239
- const middleware = expressLogger({ level: "warning" });
240
- const req = createMockRequest();
241
- const res = createMockResponse();
242
- const next: ExpressNextFunction = () => {};
243
-
244
- middleware(req, res, next);
245
- finishResponse(res);
246
-
247
- assertEquals(logs.length, 1);
248
- assertEquals(logs[0].level, "warning");
249
- } finally {
250
- await cleanup();
251
- }
252
- });
253
-
254
- test("expressLogger(): uses custom log level 'error'", async () => {
255
- const { logs, cleanup } = await setupLogtape();
256
- try {
257
- const middleware = expressLogger({ level: "error" });
258
- const req = createMockRequest();
259
- const res = createMockResponse();
260
- const next: ExpressNextFunction = () => {};
261
-
262
- middleware(req, res, next);
263
- finishResponse(res);
264
-
265
- assertEquals(logs.length, 1);
266
- assertEquals(logs[0].level, "error");
267
- } finally {
268
- await cleanup();
269
- }
270
- });
271
-
272
- // ============================================
273
- // Format Tests - Combined (default)
274
- // ============================================
275
-
276
- test("expressLogger(): combined format logs structured properties", async () => {
277
- const { logs, cleanup } = await setupLogtape();
278
- try {
279
- const middleware = expressLogger({ format: "combined" });
280
- const req = createMockRequest();
281
- const res = createMockResponse({ statusCode: 200 });
282
- res.setHeader(
283
- "content-length",
284
- "123",
285
- );
286
- const next: ExpressNextFunction = () => {};
287
-
288
- middleware(req, res, next);
289
- finishResponse(res);
290
-
291
- assertEquals(logs.length, 1);
292
- const props = logs[0].properties;
293
- assertEquals(props.method, "GET");
294
- assertEquals(props.url, "/test");
295
- assertEquals(props.status, 200);
296
- assertExists(props.responseTime);
297
- assertEquals(props.contentLength, "123");
298
- assertEquals(props.remoteAddr, "127.0.0.1");
299
- assertEquals(props.userAgent, "test-agent/1.0");
300
- assertEquals(props.referrer, "http://example.com");
301
- assertEquals(props.httpVersion, "1.1");
302
- } finally {
303
- await cleanup();
304
- }
305
- });
306
-
307
- // ============================================
308
- // Format Tests - Common
309
- // ============================================
310
-
311
- test("expressLogger(): common format excludes referrer and userAgent", async () => {
312
- const { logs, cleanup } = await setupLogtape();
313
- try {
314
- const middleware = expressLogger({ format: "common" });
315
- const req = createMockRequest();
316
- const res = createMockResponse();
317
- const next: ExpressNextFunction = () => {};
318
-
319
- middleware(req, res, next);
320
- finishResponse(res);
321
-
322
- assertEquals(logs.length, 1);
323
- const props = logs[0].properties;
324
- assertEquals(props.method, "GET");
325
- assertEquals(props.url, "/test");
326
- assertEquals(props.status, 200);
327
- assertEquals(props.referrer, undefined);
328
- assertEquals(props.userAgent, undefined);
329
- } finally {
330
- await cleanup();
331
- }
332
- });
333
-
334
- // ============================================
335
- // Format Tests - Dev
336
- // ============================================
337
-
338
- test("expressLogger(): dev format returns string message", async () => {
339
- const { logs, cleanup } = await setupLogtape();
340
- try {
341
- const middleware = expressLogger({ format: "dev" });
342
- const req = createMockRequest({
343
- method: "POST",
344
- originalUrl: "/api/users",
345
- });
346
- const res = createMockResponse({ statusCode: 201 });
347
- res.setHeader(
348
- "content-length",
349
- "456",
350
- );
351
- const next: ExpressNextFunction = () => {};
352
-
353
- middleware(req, res, next);
354
- finishResponse(res);
355
-
356
- assertEquals(logs.length, 1);
357
- const msg = logs[0].rawMessage;
358
- assert(msg.includes("POST"));
359
- assert(msg.includes("/api/users"));
360
- assert(msg.includes("201"));
361
- assert(msg.includes("ms"));
362
- assert(msg.includes("456"));
363
- } finally {
364
- await cleanup();
365
- }
366
- });
367
-
368
- // ============================================
369
- // Format Tests - Short
370
- // ============================================
371
-
372
- test("expressLogger(): short format includes remote addr", async () => {
373
- const { logs, cleanup } = await setupLogtape();
374
- try {
375
- const middleware = expressLogger({ format: "short" });
376
- const req = createMockRequest({ ip: "192.168.1.1" });
377
- const res = createMockResponse();
378
- const next: ExpressNextFunction = () => {};
379
-
380
- middleware(req, res, next);
381
- finishResponse(res);
382
-
383
- assertEquals(logs.length, 1);
384
- const msg = logs[0].rawMessage;
385
- assert(msg.includes("192.168.1.1"));
386
- assert(msg.includes("GET"));
387
- assert(msg.includes("/test"));
388
- assert(msg.includes("HTTP/1.1"));
389
- } finally {
390
- await cleanup();
391
- }
392
- });
393
-
394
- // ============================================
395
- // Format Tests - Tiny
396
- // ============================================
397
-
398
- test("expressLogger(): tiny format is minimal", async () => {
399
- const { logs, cleanup } = await setupLogtape();
400
- try {
401
- const middleware = expressLogger({ format: "tiny" });
402
- const req = createMockRequest();
403
- const res = createMockResponse({ statusCode: 404 });
404
- const next: ExpressNextFunction = () => {};
405
-
406
- middleware(req, res, next);
407
- finishResponse(res);
408
-
409
- assertEquals(logs.length, 1);
410
- const msg = logs[0].rawMessage;
411
- assert(msg.includes("GET"));
412
- assert(msg.includes("/test"));
413
- assert(msg.includes("404"));
414
- assert(msg.includes("ms"));
415
- // Should NOT include remote addr in tiny format
416
- assert(!msg.includes("127.0.0.1"));
417
- } finally {
418
- await cleanup();
419
- }
420
- });
421
-
422
- // ============================================
423
- // Custom Format Function Tests
424
- // ============================================
425
-
426
- test("expressLogger(): custom format returning string", async () => {
427
- const { logs, cleanup } = await setupLogtape();
428
- try {
429
- const middleware = expressLogger({
430
- format: (req, res, _responseTime) =>
431
- `Custom: ${req.method} ${res.statusCode}`,
432
- });
433
- const req = createMockRequest({ method: "DELETE" });
434
- const res = createMockResponse({ statusCode: 204 });
435
- const next: ExpressNextFunction = () => {};
436
-
437
- middleware(req, res, next);
438
- finishResponse(res);
439
-
440
- assertEquals(logs.length, 1);
441
- assertEquals(logs[0].rawMessage, "Custom: DELETE 204");
442
- } finally {
443
- await cleanup();
444
- }
445
- });
446
-
447
- test("expressLogger(): custom format returning object", async () => {
448
- const { logs, cleanup } = await setupLogtape();
449
- try {
450
- const middleware = expressLogger({
451
- format: (req, res, responseTime) => ({
452
- customMethod: req.method,
453
- customStatus: res.statusCode,
454
- customDuration: responseTime,
455
- }),
456
- });
457
- const req = createMockRequest({ method: "PATCH" });
458
- const res = createMockResponse({ statusCode: 202 });
459
- const next: ExpressNextFunction = () => {};
460
-
461
- middleware(req, res, next);
462
- finishResponse(res);
463
-
464
- assertEquals(logs.length, 1);
465
- assertEquals(logs[0].properties.customMethod, "PATCH");
466
- assertEquals(logs[0].properties.customStatus, 202);
467
- assertExists(logs[0].properties.customDuration);
468
- } finally {
469
- await cleanup();
470
- }
471
- });
472
-
473
- // ============================================
474
- // Skip Function Tests
475
- // ============================================
476
-
477
- test("expressLogger(): skip function prevents logging when returns true", async () => {
478
- const { logs, cleanup } = await setupLogtape();
479
- try {
480
- const middleware = expressLogger({
481
- skip: () => true,
482
- });
483
- const req = createMockRequest();
484
- const res = createMockResponse();
485
- const next: ExpressNextFunction = () => {};
486
-
487
- middleware(req, res, next);
488
- finishResponse(res);
489
-
490
- assertEquals(logs.length, 0);
491
- } finally {
492
- await cleanup();
493
- }
494
- });
495
-
496
- test("expressLogger(): skip function allows logging when returns false", async () => {
497
- const { logs, cleanup } = await setupLogtape();
498
- try {
499
- const middleware = expressLogger({
500
- skip: () => false,
501
- });
502
- const req = createMockRequest();
503
- const res = createMockResponse();
504
- const next: ExpressNextFunction = () => {};
505
-
506
- middleware(req, res, next);
507
- finishResponse(res);
508
-
509
- assertEquals(logs.length, 1);
510
- } finally {
511
- await cleanup();
512
- }
513
- });
514
-
515
- test("expressLogger(): skip function receives req and res", async () => {
516
- const { logs, cleanup } = await setupLogtape();
517
- try {
518
- const middleware = expressLogger({
519
- skip: (_req, res) => res.statusCode < 400,
520
- });
521
-
522
- // Request with 200 status - should skip
523
- const req1 = createMockRequest();
524
- const res1 = createMockResponse({ statusCode: 200 });
525
- const next: ExpressNextFunction = () => {};
526
-
527
- middleware(req1, res1, next);
528
- finishResponse(res1);
529
-
530
- assertEquals(logs.length, 0); // Skipped
531
-
532
- // Request with 500 status - should log
533
- const req2 = createMockRequest();
534
- const res2 = createMockResponse({ statusCode: 500 });
535
-
536
- middleware(req2, res2, next);
537
- finishResponse(res2);
538
-
539
- assertEquals(logs.length, 1); // Logged
540
- assertEquals(logs[0].properties.status, 500);
541
- } finally {
542
- await cleanup();
543
- }
544
- });
545
-
546
- // ============================================
547
- // Immediate Mode Tests
548
- // ============================================
549
-
550
- test("expressLogger(): immediate mode logs before response", async () => {
551
- const { logs, cleanup } = await setupLogtape();
552
- try {
553
- const middleware = expressLogger({ immediate: true });
554
- const req = createMockRequest();
555
- const res = createMockResponse();
556
- const next: ExpressNextFunction = () => {};
557
-
558
- middleware(req, res, next);
559
- // Note: Don't call finishResponse - it should already be logged
560
-
561
- assertEquals(logs.length, 1);
562
- assertEquals(logs[0].properties.responseTime, 0); // Zero because it's immediate
563
- } finally {
564
- await cleanup();
565
- }
566
- });
567
-
568
- test("expressLogger(): non-immediate mode logs after response", async () => {
569
- const { logs, cleanup } = await setupLogtape();
570
- try {
571
- const middleware = expressLogger({ immediate: false });
572
- const req = createMockRequest();
573
- const res = createMockResponse();
574
- const next: ExpressNextFunction = () => {};
575
-
576
- middleware(req, res, next);
577
-
578
- assertEquals(logs.length, 0); // Not logged yet
579
-
580
- finishResponse(res);
581
-
582
- assertEquals(logs.length, 1); // Now logged
583
- } finally {
584
- await cleanup();
585
- }
586
- });
587
-
588
- // ============================================
589
- // Request Property Tests
590
- // ============================================
591
-
592
- test("expressLogger(): logs correct method", async () => {
593
- const { logs, cleanup } = await setupLogtape();
594
- try {
595
- const middleware = expressLogger();
596
-
597
- const methods = ["GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"];
598
- for (const method of methods) {
599
- const req = createMockRequest({ method });
600
- const res = createMockResponse();
601
- const next: ExpressNextFunction = () => {};
602
-
603
- middleware(req, res, next);
604
- finishResponse(res);
605
- }
606
-
607
- assertEquals(logs.length, methods.length);
608
- for (let i = 0; i < methods.length; i++) {
609
- assertEquals(logs[i].properties.method, methods[i]);
610
- }
611
- } finally {
612
- await cleanup();
613
- }
614
- });
615
-
616
- test("expressLogger(): logs originalUrl over url", async () => {
617
- const { logs, cleanup } = await setupLogtape();
618
- try {
619
- const middleware = expressLogger();
620
- const req = createMockRequest({
621
- url: "/internal",
622
- originalUrl: "/api/v1/users",
623
- });
624
- const res = createMockResponse();
625
- const next: ExpressNextFunction = () => {};
626
-
627
- middleware(req, res, next);
628
- finishResponse(res);
629
-
630
- assertEquals(logs.length, 1);
631
- assertEquals(logs[0].properties.url, "/api/v1/users");
632
- } finally {
633
- await cleanup();
634
- }
635
- });
636
-
637
- test("expressLogger(): falls back to url when originalUrl is undefined", async () => {
638
- const { logs, cleanup } = await setupLogtape();
639
- try {
640
- const middleware = expressLogger();
641
- const req = createMockRequest({
642
- url: "/fallback",
643
- originalUrl: undefined as unknown as string,
644
- });
645
- const res = createMockResponse();
646
- const next: ExpressNextFunction = () => {};
647
-
648
- middleware(req, res, next);
649
- finishResponse(res);
650
-
651
- assertEquals(logs.length, 1);
652
- assertEquals(logs[0].properties.url, "/fallback");
653
- } finally {
654
- await cleanup();
655
- }
656
- });
657
-
658
- test("expressLogger(): logs status code", async () => {
659
- const { logs, cleanup } = await setupLogtape();
660
- try {
661
- const middleware = expressLogger();
662
-
663
- const statusCodes = [200, 201, 301, 400, 404, 500];
664
- for (const statusCode of statusCodes) {
665
- const req = createMockRequest();
666
- const res = createMockResponse({ statusCode });
667
- const next: ExpressNextFunction = () => {};
668
-
669
- middleware(req, res, next);
670
- finishResponse(res);
671
- }
672
-
673
- assertEquals(logs.length, statusCodes.length);
674
- for (let i = 0; i < statusCodes.length; i++) {
675
- assertEquals(logs[i].properties.status, statusCodes[i]);
676
- }
677
- } finally {
678
- await cleanup();
679
- }
680
- });
681
-
682
- test("expressLogger(): logs response time as number", async () => {
683
- const { logs, cleanup } = await setupLogtape();
684
- try {
685
- const middleware = expressLogger();
686
- const req = createMockRequest();
687
- const res = createMockResponse();
688
- const next: ExpressNextFunction = () => {};
689
-
690
- middleware(req, res, next);
691
-
692
- // Add small delay to ensure non-zero response time
693
- await new Promise((resolve) => setTimeout(resolve, 10));
694
-
695
- finishResponse(res);
696
-
697
- assertEquals(logs.length, 1);
698
- assertEquals(typeof logs[0].properties.responseTime, "number");
699
- assert((logs[0].properties.responseTime as number) >= 0);
700
- } finally {
701
- await cleanup();
702
- }
703
- });
704
-
705
- test("expressLogger(): logs content-length when present", async () => {
706
- const { logs, cleanup } = await setupLogtape();
707
- try {
708
- const middleware = expressLogger();
709
- const req = createMockRequest();
710
- const res = createMockResponse();
711
- res.setHeader(
712
- "content-length",
713
- "1024",
714
- );
715
- const next: ExpressNextFunction = () => {};
716
-
717
- middleware(req, res, next);
718
- finishResponse(res);
719
-
720
- assertEquals(logs.length, 1);
721
- assertEquals(logs[0].properties.contentLength, "1024");
722
- } finally {
723
- await cleanup();
724
- }
725
- });
726
-
727
- test("expressLogger(): logs undefined contentLength when not set", async () => {
728
- const { logs, cleanup } = await setupLogtape();
729
- try {
730
- const middleware = expressLogger();
731
- const req = createMockRequest();
732
- const res = createMockResponse();
733
- const next: ExpressNextFunction = () => {};
734
-
735
- middleware(req, res, next);
736
- finishResponse(res);
737
-
738
- assertEquals(logs.length, 1);
739
- assertEquals(logs[0].properties.contentLength, undefined);
740
- } finally {
741
- await cleanup();
742
- }
743
- });
744
-
745
- test("expressLogger(): logs remote address from req.ip", async () => {
746
- const { logs, cleanup } = await setupLogtape();
747
- try {
748
- const middleware = expressLogger();
749
- const req = createMockRequest({ ip: "10.0.0.1" });
750
- const res = createMockResponse();
751
- const next: ExpressNextFunction = () => {};
752
-
753
- middleware(req, res, next);
754
- finishResponse(res);
755
-
756
- assertEquals(logs.length, 1);
757
- assertEquals(logs[0].properties.remoteAddr, "10.0.0.1");
758
- } finally {
759
- await cleanup();
760
- }
761
- });
762
-
763
- test("expressLogger(): falls back to socket.remoteAddress", async () => {
764
- const { logs, cleanup } = await setupLogtape();
765
- try {
766
- const middleware = expressLogger();
767
- const req = createMockRequest({
768
- ip: undefined as unknown as string,
769
- socket: { remoteAddress: "192.168.0.1" },
770
- });
771
- const res = createMockResponse();
772
- const next: ExpressNextFunction = () => {};
773
-
774
- middleware(req, res, next);
775
- finishResponse(res);
776
-
777
- assertEquals(logs.length, 1);
778
- assertEquals(logs[0].properties.remoteAddr, "192.168.0.1");
779
- } finally {
780
- await cleanup();
781
- }
782
- });
783
-
784
- test("expressLogger(): logs HTTP version", async () => {
785
- const { logs, cleanup } = await setupLogtape();
786
- try {
787
- const middleware = expressLogger();
788
- const req = createMockRequest({ httpVersion: "2.0" });
789
- const res = createMockResponse();
790
- const next: ExpressNextFunction = () => {};
791
-
792
- middleware(req, res, next);
793
- finishResponse(res);
794
-
795
- assertEquals(logs.length, 1);
796
- assertEquals(logs[0].properties.httpVersion, "2.0");
797
- } finally {
798
- await cleanup();
799
- }
800
- });
801
-
802
- // ============================================
803
- // Multiple Requests Tests
804
- // ============================================
805
-
806
- test("expressLogger(): handles multiple sequential requests", async () => {
807
- const { logs, cleanup } = await setupLogtape();
808
- try {
809
- const middleware = expressLogger();
810
-
811
- for (let i = 0; i < 5; i++) {
812
- const req = createMockRequest({ originalUrl: `/path/${i}` });
813
- const res = createMockResponse({ statusCode: 200 + i });
814
- const next: ExpressNextFunction = () => {};
815
-
816
- middleware(req, res, next);
817
- finishResponse(res);
818
- }
819
-
820
- assertEquals(logs.length, 5);
821
- for (let i = 0; i < 5; i++) {
822
- assertEquals(logs[i].properties.url, `/path/${i}`);
823
- assertEquals(logs[i].properties.status, 200 + i);
824
- }
825
- } finally {
826
- await cleanup();
827
- }
828
- });
829
-
830
- // ============================================
831
- // Edge Cases
832
- // ============================================
833
-
834
- test("expressLogger(): handles missing user-agent", async () => {
835
- const { logs, cleanup } = await setupLogtape();
836
- try {
837
- const middleware = expressLogger();
838
- const req = createMockRequest({
839
- get: () => undefined,
840
- });
841
- const res = createMockResponse();
842
- const next: ExpressNextFunction = () => {};
843
-
844
- middleware(req, res, next);
845
- finishResponse(res);
846
-
847
- assertEquals(logs.length, 1);
848
- assertEquals(logs[0].properties.userAgent, undefined);
849
- } finally {
850
- await cleanup();
851
- }
852
- });
853
-
854
- test("expressLogger(): handles missing referrer", async () => {
855
- const { logs, cleanup } = await setupLogtape();
856
- try {
857
- const middleware = expressLogger();
858
- const req = createMockRequest({
859
- get: (header: string) => {
860
- if (header.toLowerCase() === "user-agent") return "test-agent";
861
- return undefined;
862
- },
863
- });
864
- const res = createMockResponse();
865
- const next: ExpressNextFunction = () => {};
866
-
867
- middleware(req, res, next);
868
- finishResponse(res);
869
-
870
- assertEquals(logs.length, 1);
871
- assertEquals(logs[0].properties.referrer, undefined);
872
- } finally {
873
- await cleanup();
874
- }
875
- });
package/src/mod.ts DELETED
@@ -1,411 +0,0 @@
1
- import { getLogger, type LogLevel } from "@logtape/logtape";
2
-
3
- export type { LogLevel } from "@logtape/logtape";
4
-
5
- // Use minimal type definitions for Express compatibility across Express 4.x and 5.x
6
- // These are compatible with both versions and avoid strict type checking issues
7
-
8
- /**
9
- * Minimal Express Request interface for compatibility.
10
- * @since 1.3.0
11
- */
12
- export interface ExpressRequest {
13
- method: string;
14
- url: string;
15
- originalUrl?: string;
16
- path?: string;
17
- httpVersion: string;
18
- ip?: string;
19
- socket?: { remoteAddress?: string };
20
- get(header: string): string | undefined;
21
- }
22
-
23
- /**
24
- * Minimal Express Response interface for compatibility.
25
- * @since 1.3.0
26
- */
27
- export interface ExpressResponse {
28
- statusCode: number;
29
- on(event: string, listener: () => void): void;
30
- getHeader(name: string): string | number | string[] | undefined;
31
- }
32
-
33
- /**
34
- * Express NextFunction type.
35
- * @since 1.3.0
36
- */
37
- export type ExpressNextFunction = (err?: unknown) => void;
38
-
39
- /**
40
- * Express middleware function type.
41
- * @since 1.3.0
42
- */
43
- export type ExpressMiddleware = (
44
- req: ExpressRequest,
45
- res: ExpressResponse,
46
- next: ExpressNextFunction,
47
- ) => void;
48
-
49
- /**
50
- * Predefined log format names compatible with Morgan.
51
- * @since 1.3.0
52
- */
53
- export type PredefinedFormat = "combined" | "common" | "dev" | "short" | "tiny";
54
-
55
- /**
56
- * Custom format function for request logging.
57
- *
58
- * @param req The Express request object.
59
- * @param res The Express response object.
60
- * @param responseTime The response time in milliseconds.
61
- * @returns A string message or an object with structured properties.
62
- * @since 1.3.0
63
- */
64
- export type FormatFunction = (
65
- req: ExpressRequest,
66
- res: ExpressResponse,
67
- responseTime: number,
68
- ) => string | Record<string, unknown>;
69
-
70
- /**
71
- * Structured log properties for HTTP requests.
72
- * @since 1.3.0
73
- */
74
- export interface RequestLogProperties {
75
- /** HTTP request method */
76
- method: string;
77
- /** Request URL */
78
- url: string;
79
- /** HTTP response status code */
80
- status: number;
81
- /** Response time in milliseconds */
82
- responseTime: number;
83
- /** Response content-length header value */
84
- contentLength: string | undefined;
85
- /** Remote client address */
86
- remoteAddr: string | undefined;
87
- /** User-Agent header value */
88
- userAgent: string | undefined;
89
- /** Referrer header value */
90
- referrer: string | undefined;
91
- /** HTTP version (e.g., "1.1") */
92
- httpVersion: string;
93
- }
94
-
95
- /**
96
- * Options for configuring the Express LogTape middleware.
97
- * @since 1.3.0
98
- */
99
- export interface ExpressLogTapeOptions {
100
- /**
101
- * The LogTape category to use for logging.
102
- * @default ["express"]
103
- */
104
- readonly category?: string | readonly string[];
105
-
106
- /**
107
- * The log level to use for request logging.
108
- * @default "info"
109
- */
110
- readonly level?: LogLevel;
111
-
112
- /**
113
- * The format for log output.
114
- * Can be a predefined format name or a custom format function.
115
- *
116
- * Predefined formats:
117
- * - `"combined"` - Apache Combined Log Format (structured, default)
118
- * - `"common"` - Apache Common Log Format (structured, no referrer/userAgent)
119
- * - `"dev"` - Concise colored output for development (string)
120
- * - `"short"` - Shorter than common (string)
121
- * - `"tiny"` - Minimal output (string)
122
- *
123
- * @default "combined"
124
- */
125
- readonly format?: PredefinedFormat | FormatFunction;
126
-
127
- /**
128
- * Function to determine whether logging should be skipped.
129
- * Return `true` to skip logging for a request.
130
- *
131
- * @example Skip logging for successful requests
132
- * ```typescript
133
- * app.use(expressLogger({
134
- * skip: (req, res) => res.statusCode < 400,
135
- * }));
136
- * ```
137
- *
138
- * @default () => false
139
- */
140
- readonly skip?: (req: ExpressRequest, res: ExpressResponse) => boolean;
141
-
142
- /**
143
- * If `true`, logs are written immediately when the request is received.
144
- * If `false` (default), logs are written after the response is sent.
145
- *
146
- * Note: When `immediate` is `true`, response-related properties
147
- * (status, responseTime, contentLength) will not be available.
148
- *
149
- * @default false
150
- */
151
- readonly immediate?: boolean;
152
- }
153
-
154
- /**
155
- * Get remote address from request.
156
- */
157
- function getRemoteAddr(req: ExpressRequest): string | undefined {
158
- return req.ip || req.socket?.remoteAddress;
159
- }
160
-
161
- /**
162
- * Get content length from response headers.
163
- */
164
- function getContentLength(res: ExpressResponse): string | undefined {
165
- const contentLength = res.getHeader("content-length");
166
- if (contentLength === undefined || contentLength === null) return undefined;
167
- return String(contentLength);
168
- }
169
-
170
- /**
171
- * Get referrer from request headers.
172
- */
173
- function getReferrer(req: ExpressRequest): string | undefined {
174
- return req.get("referrer") || req.get("referer");
175
- }
176
-
177
- /**
178
- * Get user agent from request headers.
179
- */
180
- function getUserAgent(req: ExpressRequest): string | undefined {
181
- return req.get("user-agent");
182
- }
183
-
184
- /**
185
- * Build structured log properties from request/response.
186
- */
187
- function buildProperties(
188
- req: ExpressRequest,
189
- res: ExpressResponse,
190
- responseTime: number,
191
- ): RequestLogProperties {
192
- return {
193
- method: req.method,
194
- url: req.originalUrl || req.url,
195
- status: res.statusCode,
196
- responseTime,
197
- contentLength: getContentLength(res),
198
- remoteAddr: getRemoteAddr(req),
199
- userAgent: getUserAgent(req),
200
- referrer: getReferrer(req),
201
- httpVersion: req.httpVersion,
202
- };
203
- }
204
-
205
- /**
206
- * Combined format (Apache Combined Log Format).
207
- * Returns all structured properties.
208
- */
209
- function formatCombined(
210
- req: ExpressRequest,
211
- res: ExpressResponse,
212
- responseTime: number,
213
- ): Record<string, unknown> {
214
- return { ...buildProperties(req, res, responseTime) };
215
- }
216
-
217
- /**
218
- * Common format (Apache Common Log Format).
219
- * Like combined but without referrer and userAgent.
220
- */
221
- function formatCommon(
222
- req: ExpressRequest,
223
- res: ExpressResponse,
224
- responseTime: number,
225
- ): Record<string, unknown> {
226
- const props = buildProperties(req, res, responseTime);
227
- const { referrer: _referrer, userAgent: _userAgent, ...rest } = props;
228
- return rest;
229
- }
230
-
231
- /**
232
- * Dev format (colored output for development).
233
- * :method :url :status :response-time ms - :res[content-length]
234
- */
235
- function formatDev(
236
- req: ExpressRequest,
237
- res: ExpressResponse,
238
- responseTime: number,
239
- ): string {
240
- const contentLength = getContentLength(res) ?? "-";
241
- return `${req.method} ${req.originalUrl || req.url} ${res.statusCode} ${
242
- responseTime.toFixed(3)
243
- } ms - ${contentLength}`;
244
- }
245
-
246
- /**
247
- * Short format.
248
- * :remote-addr :method :url HTTP/:http-version :status :res[content-length] - :response-time ms
249
- */
250
- function formatShort(
251
- req: ExpressRequest,
252
- res: ExpressResponse,
253
- responseTime: number,
254
- ): string {
255
- const remoteAddr = getRemoteAddr(req) ?? "-";
256
- const contentLength = getContentLength(res) ?? "-";
257
- return `${remoteAddr} ${req.method} ${
258
- req.originalUrl || req.url
259
- } HTTP/${req.httpVersion} ${res.statusCode} ${contentLength} - ${
260
- responseTime.toFixed(3)
261
- } ms`;
262
- }
263
-
264
- /**
265
- * Tiny format (minimal output).
266
- * :method :url :status :res[content-length] - :response-time ms
267
- */
268
- function formatTiny(
269
- req: ExpressRequest,
270
- res: ExpressResponse,
271
- responseTime: number,
272
- ): string {
273
- const contentLength = getContentLength(res) ?? "-";
274
- return `${req.method} ${
275
- req.originalUrl || req.url
276
- } ${res.statusCode} ${contentLength} - ${responseTime.toFixed(3)} ms`;
277
- }
278
-
279
- /**
280
- * Map of predefined format functions.
281
- */
282
- const predefinedFormats: Record<PredefinedFormat, FormatFunction> = {
283
- combined: formatCombined,
284
- common: formatCommon,
285
- dev: formatDev,
286
- short: formatShort,
287
- tiny: formatTiny,
288
- };
289
-
290
- /**
291
- * Normalize category to array format.
292
- */
293
- function normalizeCategory(
294
- category: string | readonly string[],
295
- ): readonly string[] {
296
- return typeof category === "string" ? [category] : category;
297
- }
298
-
299
- /**
300
- * Creates Express middleware for HTTP request logging using LogTape.
301
- *
302
- * This middleware provides Morgan-compatible request logging with LogTape
303
- * as the backend, supporting structured logging and customizable formats.
304
- *
305
- * @example Basic usage
306
- * ```typescript
307
- * import express from "express";
308
- * import { configure, getConsoleSink } from "@logtape/logtape";
309
- * import { expressLogger } from "@logtape/express";
310
- *
311
- * await configure({
312
- * sinks: { console: getConsoleSink() },
313
- * loggers: [
314
- * { category: ["express"], sinks: ["console"], lowestLevel: "info" }
315
- * ],
316
- * });
317
- *
318
- * const app = express();
319
- * app.use(expressLogger());
320
- *
321
- * app.get("/", (req, res) => {
322
- * res.json({ hello: "world" });
323
- * });
324
- *
325
- * app.listen(3000);
326
- * ```
327
- *
328
- * @example With custom options
329
- * ```typescript
330
- * app.use(expressLogger({
331
- * category: ["myapp", "http"],
332
- * level: "debug",
333
- * format: "dev",
334
- * skip: (req, res) => res.statusCode < 400,
335
- * }));
336
- * ```
337
- *
338
- * @example With custom format function
339
- * ```typescript
340
- * app.use(expressLogger({
341
- * format: (req, res, responseTime) => ({
342
- * method: req.method,
343
- * path: req.path,
344
- * status: res.statusCode,
345
- * duration: responseTime,
346
- * }),
347
- * }));
348
- * ```
349
- *
350
- * @param options Configuration options for the middleware.
351
- * @returns Express middleware function.
352
- * @since 1.3.0
353
- */
354
- export function expressLogger(
355
- options: ExpressLogTapeOptions = {},
356
- ): ExpressMiddleware {
357
- const category = normalizeCategory(options.category ?? ["express"]);
358
- const logger = getLogger(category);
359
- const level = options.level ?? "info";
360
- const formatOption = options.format ?? "combined";
361
- const skip = options.skip ?? (() => false);
362
- const immediate = options.immediate ?? false;
363
-
364
- // Resolve format function
365
- const formatFn: FormatFunction = typeof formatOption === "string"
366
- ? predefinedFormats[formatOption]
367
- : formatOption;
368
-
369
- const logMethod = logger[level].bind(logger);
370
-
371
- return (
372
- req: ExpressRequest,
373
- res: ExpressResponse,
374
- next: ExpressNextFunction,
375
- ): void => {
376
- const startTime = Date.now();
377
-
378
- // For immediate logging, log when request arrives
379
- if (immediate) {
380
- if (!skip(req, res)) {
381
- const result = formatFn(req, res, 0);
382
- if (typeof result === "string") {
383
- logMethod(result);
384
- } else {
385
- logMethod("{method} {url}", result);
386
- }
387
- }
388
- next();
389
- return;
390
- }
391
-
392
- // Log after response is sent
393
- const logRequest = (): void => {
394
- if (skip(req, res)) return;
395
-
396
- const responseTime = Date.now() - startTime;
397
- const result = formatFn(req, res, responseTime);
398
-
399
- if (typeof result === "string") {
400
- logMethod(result);
401
- } else {
402
- logMethod("{method} {url} {status} - {responseTime} ms", result);
403
- }
404
- };
405
-
406
- // Listen for response finish event
407
- res.on("finish", logRequest);
408
-
409
- next();
410
- };
411
- }
package/tsdown.config.ts DELETED
@@ -1,11 +0,0 @@
1
- import { defineConfig } from "tsdown";
2
-
3
- export default defineConfig({
4
- entry: "src/mod.ts",
5
- dts: {
6
- sourcemap: true,
7
- },
8
- format: ["esm", "cjs"],
9
- platform: "node",
10
- unbundle: true,
11
- });