File size: 860 Bytes
15f4599
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c114c72
15f4599
 
c114c72
15f4599
 
 
 
 
 
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
import { Injectable, NestMiddleware, Logger } from '@nestjs/common';

import { Request, Response, NextFunction } from 'express';

@Injectable()
export class AppLoggerMiddleware implements NestMiddleware {
  private logger = new Logger();

  use(request: Request, response: Response, next: NextFunction): void {
    const { ip, method, baseUrl: url } = request;
    const userAgent = request.get('user-agent') || '';

    response.on('close', () => {
      const { statusCode } = response;
      const contentLength = response.get('content-length');

      const queries = Object.entries(request.query);
      const appendUrl = queries.map((query) => query.join('=')).join('&');

      this.logger.log(
        `${method} ${url + (queries.length ? '?' + appendUrl : '')} ${statusCode} ${contentLength} - ${userAgent} ${ip}`,
      );
    });

    next();
  }
}