| 1 | import { |
| 2 | CallHandler, |
| 3 | ExecutionContext, |
| 4 | Injectable, |
| 5 | Logger, |
| 6 | NestInterceptor, |
| 7 | } from '@nestjs/common'; |
| 8 | import { Observable, tap } from 'rxjs'; |
| 9 | |
| 10 | @Injectable() |
| 11 | export class LoggingInterceptor implements NestInterceptor { |
| 12 | private logger = new Logger(LoggingInterceptor.name, { timestamp: false }); |
| 13 | |
| 14 | intercept( |
| 15 | context: ExecutionContext, |
| 16 | next: CallHandler<any>, |
| 17 | ): Observable<any> { |
| 18 | const call$ = next.handle(); |
| 19 | const request = context.switchToHttp().getRequest(); |
| 20 | const content = `${request.method} -> ${request.url}`; |
| 21 | const isSse = request.headers.accept === 'text/event-stream'; |
| 22 | this.logger.debug(`+++ 请求:${content}`); |
| 23 | const now = Date.now(); |
| 24 | |
| 25 | return call$.pipe( |
| 26 | tap(() => { |
| 27 | if (isSse) return; |
| 28 | |
| 29 | this.logger.debug(`--- 响应:${content}${` +${Date.now() - now}ms`}`); |
| 30 | }), |
| 31 | ); |
| 32 | } |
| 33 | } |
| 34 |