forked from PinSpace-Org/GistPin
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlogging.interceptor.ts
More file actions
41 lines (35 loc) · 1.4 KB
/
Copy pathlogging.interceptor.ts
File metadata and controls
41 lines (35 loc) · 1.4 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
import { Injectable, NestInterceptor, ExecutionContext, CallHandler, Logger } from '@nestjs/common';
import { Observable, tap } from 'rxjs';
import { Request, Response } from 'express';
import { getCorrelationId } from '../logger/correlation-id.store';
@Injectable()
export class LoggingInterceptor implements NestInterceptor {
private readonly logger = new Logger('HTTP');
intercept(context: ExecutionContext, next: CallHandler): Observable<unknown> {
const req = context.switchToHttp().getRequest<Request>();
const res = context.switchToHttp().getResponse<Response>();
const { method, url, ip } = req;
if (url.startsWith('/health')) {
return next.handle();
}
const start = Date.now();
return next.handle().pipe(
tap({
next: () => {
const ms = Date.now() - start;
const status = res.statusCode;
const correlationId = getCorrelationId();
const log = `${method} ${url} ${status} ${ms}ms — ${ip} [${correlationId}]`;
if (status >= 500) this.logger.error(log);
else if (status >= 400) this.logger.warn(log);
else this.logger.log(log);
},
error: (err: Error) => {
const ms = Date.now() - start;
const correlationId = getCorrelationId();
this.logger.error(`${method} ${url} ERROR ${ms}ms [${correlationId}] — ${err.message}`);
},
}),
);
}
}