Skip to content

Commit

Permalink
[CHORE] nestjs logger 개선 #26
Browse files Browse the repository at this point in the history
  • Loading branch information
rdd9223 committed May 19, 2024
1 parent 19aaacc commit 314a2e4
Show file tree
Hide file tree
Showing 3 changed files with 44 additions and 3 deletions.
9 changes: 7 additions & 2 deletions server/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 } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { MeetingModule } from './meeting/meeting.module';
import { ConfigModule, ConfigService } from '@nestjs/config';
Expand All @@ -10,6 +10,7 @@ import { TransformInterceptor } from './common/interceptor/transform.interceptor
import { NoticeModule } from './notice/notice.module';
import { PostModule } from './post/post.module';
import { CommentModule } from './comment/comment.module';
import { LoggerMiddleware } from './common/middleware/logger.middleware';

@Module({
imports: [
Expand Down Expand Up @@ -46,4 +47,8 @@ import { CommentModule } from './comment/comment.module';
},
],
})
export class AppModule {}
export class AppModule {
configure(consumer: MiddlewareConsumer) {
consumer.apply(LoggerMiddleware).forRoutes('*');
}
}
31 changes: 31 additions & 0 deletions server/src/common/middleware/logger.middleware.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import { Injectable, Logger, NestMiddleware } from '@nestjs/common';
import { NextFunction, Request, Response } from 'express';

@Injectable()
export class LoggerMiddleware implements NestMiddleware {
private readonly logger = new Logger('HTTP');

use(request: Request, response: Response, next: NextFunction) {
const start = Date.now();

response.on('finish', () => {
const { method, originalUrl } = request;
const { statusCode, statusMessage } = response;
const duration = Date.now() - start;

const message = `[${duration}ms] ${method} ${originalUrl} ${statusCode} ${statusMessage}`;

if (statusCode >= 500) {
return this.logger.error(message);
}

if (statusCode >= 400) {
return this.logger.warn(message);
}

return this.logger.log(message);
});

next();
}
}
7 changes: 6 additions & 1 deletion server/src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,12 @@ import { setupSwagger } from './common/utils/swagger';
async function bootstrap() {
const app = await NestFactory.create(AppModule, {
cors: true,
bufferLogs: true,
logger:
process.env.NODE_ENV === 'production'
? ['log', 'error', 'warn']
: ['log', 'error', 'warn', 'debug', 'verbose'],
});

setupSwagger(app);
app.useGlobalPipes(
new ValidationPipe({
Expand All @@ -23,4 +27,5 @@ async function bootstrap() {
const port = process.env.PORT || 3000;
await app.listen(port);
}

bootstrap();

0 comments on commit 314a2e4

Please sign in to comment.