web-backset.cn/apps/server2/src/interceptor/logging.interceptor.ts
2023-02-16 17:58:27 +08:00

34 lines
1.0 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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`,
);
}),
);
}
}