-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlogger.middleware.ts
executable file
·30 lines (23 loc) · 1.04 KB
/
logger.middleware.ts
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
import { Injectable, NestMiddleware } from '@nestjs/common';
import { webcrypto } from 'crypto';
import type { Request, Response } from 'express';
import { Logger } from '../providers';
@Injectable()
export class LoggerMiddleware implements NestMiddleware {
private passUrl: string[] = ['/health', '/graphql'];
// GraphQL logging uses the apollo plugins.
// https://docs.nestjs.com/graphql/plugins
// https://www.apollographql.com/docs/apollo-server/integrations/plugins/
// https://github.com/nestjs/graphql/issues/923
constructor(private readonly logger: Logger) {}
public use(req: Request, res: Response, next: () => void): void {
if (this.passUrl.includes(req.originalUrl)) {
return next();
}
req.id = req.header('X-Request-Id') || webcrypto.randomUUID();
res.setHeader('X-Request-Id', req.id);
const user = req.user?.userId || '';
this.logger.log(`${req.method} ${req.originalUrl} - ${String(req.ip).replace('::ffff:', '')} ${user}`);
return next();
}
}