forked from ZyntariHQ/Invoisio
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlogging.interceptor.ts
More file actions
62 lines (56 loc) · 1.83 KB
/
Copy pathlogging.interceptor.ts
File metadata and controls
62 lines (56 loc) · 1.83 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
import {
CallHandler,
ExecutionContext,
Injectable,
NestInterceptor,
} from "@nestjs/common";
import { Observable, tap } from "rxjs";
import { Request, Response } from "express";
import { StructuredLogger } from "./structured-logger.service";
import { RequestContextService } from "./request-context.service";
@Injectable()
export class LoggingInterceptor implements NestInterceptor {
constructor(
private readonly logger: StructuredLogger,
private readonly requestContext: RequestContextService,
) {}
intercept(context: ExecutionContext, next: CallHandler): Observable<unknown> {
if (context.getType() !== "http") {
return next.handle();
}
const req = context.switchToHttp().getRequest<Request>();
const res = context.switchToHttp().getResponse<Response>();
const startedAt = Date.now();
const user = (
req as Request & { user?: { id?: string; merchantId?: string } }
).user;
if (user?.id || user?.merchantId) {
this.requestContext.setUserContext(user.id, user.merchantId ?? undefined);
}
this.logger.info("http.request.start", {
method: req.method,
path: req.originalUrl ?? req.url,
});
return next.handle().pipe(
tap({
next: () => {
this.logger.info("http.request.complete", {
method: req.method,
path: req.originalUrl ?? req.url,
statusCode: res.statusCode,
durationMs: Date.now() - startedAt,
});
},
error: (error: unknown) => {
this.logger.error("http.request.error", {
method: req.method,
path: req.originalUrl ?? req.url,
statusCode: res.statusCode,
durationMs: Date.now() - startedAt,
error: error instanceof Error ? error.message : String(error),
});
},
}),
);
}
}