-
Notifications
You must be signed in to change notification settings - Fork 57
Expand file tree
/
Copy pathrequestLogger.ts
More file actions
73 lines (60 loc) · 1.62 KB
/
Copy pathrequestLogger.ts
File metadata and controls
73 lines (60 loc) · 1.62 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
import type { Request, Response, NextFunction } from "express";
import { randomUUID } from "crypto";
import { logger } from "../utils/logger.js";
export const REQUEST_ID_HEADER = "x-request-id";
/**
* Extend Express Request to include requestId
*/
declare module "express-serve-static-core" {
interface Request {
requestId?: string;
}
}
function sanitizeWallet(address?: string): string | undefined {
if (!address || typeof address !== "string") return undefined;
// Truncate to avoid logging full PII
return `${address.slice(0, 6)}...${address.slice(-4)}`;
}
export function requestLogger(
req: Request,
res: Response,
next: NextFunction,
): void {
const start = Date.now();
// 1. Get or generate requestId
const incomingId = req.headers[REQUEST_ID_HEADER] as string | undefined;
const requestId = incomingId ?? randomUUID();
// 2. Attach to request
req.requestId = requestId;
// 3. Attach to response
res.setHeader(REQUEST_ID_HEADER, requestId);
// 4. Log request start
logger.info(
{
requestId,
method: req.method,
path: req.originalUrl,
},
"request:start",
);
// 5. Log response finish
res.on("finish", () => {
const duration = Date.now() - start;
const wallet =
typeof req.body?.walletAddress === "string"
? sanitizeWallet(req.body.walletAddress)
: undefined;
logger.info(
{
requestId,
method: req.method,
path: req.originalUrl,
statusCode: res.statusCode,
durationMs: duration,
walletAddress: wallet, // sanitized
},
"request:end",
);
});
next();
}