Skip to content

Commit

Permalink
[BE#233] Logger 요청부터 응답까지의 시간 측정
Browse files Browse the repository at this point in the history
  • Loading branch information
yeongbinim authored Nov 28, 2023
1 parent adb86da commit b3ebc29
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 16 deletions.
9 changes: 7 additions & 2 deletions BE/src/app.module.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Module } from '@nestjs/common';
import { MiddlewareConsumer, Module, NestModule } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { TypeOrmModule } from '@nestjs/typeorm';
Expand All @@ -15,6 +15,7 @@ import { AuthModule } from './auth/auth.module';
import { ServeStaticModule } from '@nestjs/serve-static';
import { join } from 'path';
import { Mates } from './mates/mates.entity';
import { LoggingMiddleware } from './common/logging.middleware';

@Module({
imports: [
Expand Down Expand Up @@ -49,4 +50,8 @@ import { Mates } from './mates/mates.entity';
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}
export class AppModule implements NestModule {
configure(consumer: MiddlewareConsumer) {
consumer.apply(LoggingMiddleware).forRoutes('*');
}
}
26 changes: 12 additions & 14 deletions BE/src/common/logging.interceptor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,20 +17,18 @@ export class LoggingInterceptor implements NestInterceptor {
const response = ctx.getResponse();
const { method, url, body } = request;

this.logger.debug(
`[Request] Method: ${method}, URL: ${url}, Body: ${JSON.stringify(body)}`,
this.logger.debug(`[Request] ${method} ${url} \n ${JSON.stringify(body)}`);
return next.handle().pipe(
tap((body) => {
const requestToResponse: `${number}ms` = `${
Date.now() - request.now
}ms`;
this.logger.debug(
`[Response] ${
response.statusCode
} ${requestToResponse} \n ${JSON.stringify(body)} \n`,
);
}),
);

return next
.handle()
.pipe(
tap((body) =>
this.logger.debug(
`[Response] Status: ${response.statusCode}, Body: ${JSON.stringify(
body,
)}`,
),
),
);
}
}
10 changes: 10 additions & 0 deletions BE/src/common/logging.middleware.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { Injectable, NestMiddleware } from '@nestjs/common';
import { NextFunction } from 'express';

@Injectable()
export class LoggingMiddleware implements NestMiddleware {
use(req: Request & { now: number }, res: Response, next: NextFunction) {
req.now = Date.now();
next();
}
}

0 comments on commit b3ebc29

Please sign in to comment.