是Nest.js的新手,
我正在尝试实现一个简单的记录器来跟踪HTTP请求,例如:
:method :url :status :res[content-length] - :response-time ms根据我的理解,最好的选择是拦截器。但我也使用守卫,正如我所提到的,警卫在中间件之后触发,而在拦截器之前触发。
意思是,我禁止的访问没有被记录。我可以在两个不同的地方编写日志记录部分,而不是。有什么想法吗?
谢谢!
我的拦截器代码:
import { Injectable, NestInterceptor, ExecutionContext, HttpException, HttpStatus } from '@nestjs/common';
import { Observable, throwError } from 'rxjs';
import { catchError, tap } from 'rxjs/operators';
@Injectable()
export class HTTPLoggingInterceptor implements NestInterceptor {
intercept(context: ExecutionContext, call$: Observable<any>): Observable<any> {
const now = Date.now();
const request = context.switchToHttp().getRequest();
const method = request.method;
const url = request.originalUrl;
return call$.pipe(
tap(() => {
const response = context.switchToHttp().getResponse();
const delay = Date.now() - now;
console.log(`${response.statusCode} | [${method}] ${url} - ${delay}ms`);
}),
catchError((error) => {
const response = context.switchToHttp().getResponse();
const delay = Date.now() - now;
console.error(`${response.statusCode} | [${method}] ${url} - ${delay}ms`);
return throwError(error);
}),
);
}
}发布于 2019-07-02 15:25:11
最后,我在原始应用程序上注入了一个经典的记录器。这个解决方案并不是最好的解决方案,因为它没有集成到Nest流中,而是很适合标准日志记录需求。
import { NestFactory } from '@nestjs/core';
import { FastifyAdapter, NestFastifyApplication } from '@nestjs/platform-fastify';
import { ApplicationModule } from './app.module';
import * as morgan from 'morgan';
async function bootstrap() {
const app = await NestFactory.create<NestFastifyApplication>(ApplicationModule, new FastifyAdapter());
app.use(morgan('tiny'));
await app.listen(process.env.PORT, '0.0.0.0');
}
if (isNaN(parseInt(process.env.PORT))) {
console.error('No port provided. ');
process.exit(666);
}
bootstrap().then(() => console.log('Service listening : ', process.env.PORT));发布于 2020-09-17 08:48:47
https://github.com/julien-sarazin/nest-playground/issues/1#issuecomment-682588094
您可以为此使用中间件。
import { Injectable, NestMiddleware, Logger } from '@nestjs/common';
import { Request, Response, NextFunction } from 'express';
@Injectable()
export class AppLoggerMiddleware implements NestMiddleware {
private logger = new Logger('HTTP');
use(request: Request, response: Response, next: NextFunction): void {
const { ip, method, path: url } = request;
const userAgent = request.get('user-agent') || '';
response.on('close', () => {
const { statusCode } = response;
const contentLength = response.get('content-length');
this.logger.log(
`${method} ${url} ${statusCode} ${contentLength} - ${userAgent} ${ip}`
);
});
next();
}
}在AppModule中
export class AppModule implements NestModule {
configure(consumer: MiddlewareConsumer): void {
consumer.apply(AppLoggerMiddleware).forRoutes('*');
}
}发布于 2020-12-03 09:04:05
不如使用finish事件而不是close事件。
import { Request, Response, NextFunction } from "express";
import { Injectable, NestMiddleware, Logger } from "@nestjs/common";
@Injectable()
export class LoggerMiddleware implements NestMiddleware {
private logger = new Logger("HTTP");
use(request: Request, response: Response, next: NextFunction): void {
const { ip, method, originalUrl } = request;
const userAgent = request.get("user-agent") || "";
response.on("finish", () => {
const { statusCode } = response;
const contentLength = response.get("content-length");
this.logger.log(
`${method} ${originalUrl} ${statusCode} ${contentLength} - ${userAgent} ${ip}`,
);
});
next();
}
}因为据了解,express连接是在发送响应后维护的。
所以不能触发close事件
参考文献
事件。
https://stackoverflow.com/questions/55093055
复制相似问题