首页  编辑  

Controller方法调用日志的拦截器

Tags: /Node & JS/   Date Created:
Nodejs环境,nest 框架,实现类似 Java/SpringBoot下的 @Log 注解方式对Controller调用写日志:

首先创建 log.ts:
import { CallHandler, ExecutionContext, Injectable, NestInterceptor } from '@nestjs/common';
import 'reflect-metadata';
import { Observable } from 'rxjs';
import { tap } from 'rxjs/operators';


@Injectable()
export class LogInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    const className = context.getClass().name;
    const name = context.getHandler().name;
    const request = context.switchToHttp().getRequest();
    const logger = new Logger(className);

    const token = request.headers['accesstoken'];
    logger.info(name, `Call open: ${className}.${name}, token: ${token}`);
    const start = Date.now();
    return next.handle().pipe(tap(() =>
      logger.info(name, `Call done: ${className}.${name}, duration: ${Date.now() - start}ms`)
    ));
  }

}
然后在 NestController 类或者方法上,使用 @UseInterceptors(new LogInterceptor) 注解即可
import { LogInterceptor } from 'log';
@UseInterceptors(new LogInterceptor)
export class XxxController {
}
上述的方法,对所有的Controller其作用,对service或者其他的类不能起作用。