34 lines
1.0 KiB
TypeScript
34 lines
1.0 KiB
TypeScript
import {
|
||
Injectable,
|
||
NestInterceptor,
|
||
ExecutionContext,
|
||
CallHandler,
|
||
Logger,
|
||
} from '@nestjs/common';
|
||
import { Request } from 'express';
|
||
import { Observable } from 'rxjs';
|
||
import { tap } from 'rxjs/operators';
|
||
// import dayjs = require('dayjs');
|
||
// dayjs().format('{YYYY} MM-DDTHH:mm:ss')
|
||
|
||
@Injectable()
|
||
export class LoggingInterceptor implements NestInterceptor {
|
||
private readonly logger = new Logger('request'); // 实例化日志记录器
|
||
|
||
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
|
||
const start = Date.now(); // 请求开始时间
|
||
|
||
return next.handle().pipe(
|
||
tap(() => {
|
||
// 调用完handle()后得到RxJs响应对象,使用tap可以得到路由函数的返回值
|
||
const host = context.switchToHttp();
|
||
const request = host.getRequest<Request>();
|
||
// 打印请求方法,请求链接,处理时间和响应数据
|
||
this.logger.log(
|
||
`${request.method} ${request.url} ${Date.now() - start} ms`,
|
||
);
|
||
}),
|
||
);
|
||
}
|
||
}
|