forked from CatsMiaow/nestjs-project-structure
-
Notifications
You must be signed in to change notification settings - Fork 0
/
logger.middleware.ts
executable file
·32 lines (25 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
31
32
import { Injectable, NestMiddleware } from '@nestjs/common';
import type { Request, Response } from 'express';
import { nanoid } from 'nanoid';
import { Logger } from '../logger';
@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') || nanoid();
res.setHeader('X-Request-Id', req.id);
// Uncomment when using PinoLogger
// Logger.setMetadata({ id: req.id });
const user = req.user?.userId || '';
this.logger.log(`${req.method} ${req.originalUrl} - ${req.ip.replace('::ffff:', '')} ${user}`);
return next();
}
}