Skip to content

Commit

Permalink
Merge pull request #54 from plus-tdd/feature/counseling
Browse files Browse the repository at this point in the history
로거미들웨어 구현
  • Loading branch information
codeing999 authored Jul 26, 2023
2 parents 0957953 + ba0e95f commit 20fc554
Show file tree
Hide file tree
Showing 7 changed files with 80 additions and 10 deletions.
3 changes: 2 additions & 1 deletion src/app.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@ export class AppController {
@Get()
getHello(): { statusCode: number; data: string } {
const logger = new Logger('application.app.controller');
logger.info('안녕하세요', '대문입니다.');
console.log('???');
logger.info('안녕하세요', '재철대문입니다.');
const data = this.appService.getHello();
return { statusCode: 200, data };
}
Expand Down
9 changes: 7 additions & 2 deletions 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 { CounselingModule } from './module/counseling/counseling.module';
Expand All @@ -25,6 +25,7 @@ import { AlarmModule } from './module/alarm/alarm.module';
import { AlarmServiceImpl } from './module/alarm/alarm.service';
import { DoctorModule } from './module/doctor/doctor.module';
import { DoctorEntity } from './module/doctor/data/doctor.entity';
import { LoggerMiddleware } from './logger/logger.middleware';

// Module 설명 : express에서는 router위주의 설계였다면, nest에서는 module위주의 설계를 한다
// 기능별로 module을 만들어서 여기에 다 넣어줄거임 - nest가 module간의 연결된걸 파악해서 한번에 실행해줌
Expand Down Expand Up @@ -74,4 +75,8 @@ import { DoctorEntity } from './module/doctor/data/doctor.entity';
AlarmServiceImpl,
],
})
export class AppModule {}
export class AppModule implements NestModule {
configure(consumer: MiddlewareConsumer) {
consumer.apply(LoggerMiddleware).forRoutes('*');
}
}
4 changes: 3 additions & 1 deletion src/logger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ import moment from 'moment-timezone';

const { createLogger, transports } = winston;
const { combine, timestamp, colorize, printf, errors } = winston.format;
const now = moment().format('YYYY-MM-DD HH:mm:ss');

export default class Logger {
private logger: winston.Logger;
Expand Down Expand Up @@ -66,6 +65,7 @@ export default class Logger {
}

public info(msg: string, metadata = '') {
const now = moment().format('YYYY-MM-DD HH:mm:ss');
this.logger.info(msg);
if (this.is_production) {
const info = {
Expand All @@ -79,6 +79,7 @@ export default class Logger {
}
}
public error(errMsg: Error | string, metadata = '') {
const now = moment().format('YYYY-MM-DD HH:mm:ss');
if (errMsg instanceof Error) {
const err = errMsg.stack ? errMsg.stack : errMsg.message;
this.logger.error(err + '\n --metadata->' + metadata); // this will now log the error stack trace
Expand All @@ -100,6 +101,7 @@ export default class Logger {
this.logger.debug(debugMsg);
}
public warn(warnMsg: string, metadata = '') {
const now = moment().format('YYYY-MM-DD HH:mm:ss');
this.logger.warn(warnMsg);
if (this.is_production) {
const info = {
Expand Down
7 changes: 7 additions & 0 deletions src/logger/logger.middleware.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { LoggerMiddleware } from './logger.middleware';

describe('LoggerMiddleware', () => {
it('should be defined', () => {
expect(new LoggerMiddleware()).toBeDefined();
});
});
50 changes: 50 additions & 0 deletions src/logger/logger.middleware.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import { Injectable, NestMiddleware } from '@nestjs/common';
import { Request, Response, NextFunction } from 'express';
import Logger from './../logger';

@Injectable()
export class LoggerMiddleware implements NestMiddleware {
private logger = new Logger(process.env.NODE_ENV);
use(req: Request, res: Response, next: NextFunction) {
const { method, originalUrl: url, params, query, body, headers } = req;

const originalSend = res.send;
res.send = function (body) {
const responseBody = body instanceof Object ? JSON.stringify(body) : body;
const { method, originalUrl: url } = req;
const statusCode = res.statusCode;

// 응답 전송
res.send = originalSend;
res.send(body);

// 로그 남기기
this.logger.info(
`${method} ${url} StatusCode: ${statusCode}\n[REQUEST] \nParams: ${JSON.stringify(
params,
)} \nQuery: ${JSON.stringify(query)} \nBody: ${JSON.stringify(
body,
)} \nHeaders: ${JSON.stringify(
headers,
)} \n[RESPONSE] \n \nBody: ${responseBody}`,
);
}.bind(this);

// res.on('finish', () => {
// console.log(
// 'ip:',
// req.ip,
// 'method:',
// req.method,
// 'statusCode:',
// res.statusCode,
// );
// this.logger.info(
// `${req.ip} ${req.method} ${res.statusCode} ${res.ResBody}`,
// req.originalUrl,
// );
// });

next();
}
}
14 changes: 9 additions & 5 deletions src/module/counseling/api/counseling.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import {
counselingDataBaseError,
} from './../counseling.error';
import { Response } from './../../../response';
import { Counseling } from '../domain/counseling.model';

@Controller('counseling')
export class CounselingController {
Expand All @@ -41,8 +42,8 @@ export class CounselingController {
counselingInfo,
);
return this.response.success(result);
} catch (error) {
throw error;
} catch (e) {
throw e;
}
}

Expand All @@ -59,18 +60,21 @@ export class CounselingController {
);

const response = result.map((v) => this.mapper.mapDomainToDto(v));
console.log(response);
return response;
}

@UseGuards(JwtAuthGuard)
@ApiOperation({ summary: '진료 상세 조회' })
@Get(':id')
async getCounseling(@Param('id') counselingId: string) {
const result = await this.counselingService.getCounseling(counselingId);
let result: Counseling;
try {
result = await this.counselingService.getCounseling(counselingId);
} catch (e) {
throw e;
}

const response = this.mapper.mapDomainToDto(result);
console.log(response);
return response;
}

Expand Down
3 changes: 2 additions & 1 deletion src/module/counseling/data/counseling.db.ts
Original file line number Diff line number Diff line change
Expand Up @@ -145,7 +145,8 @@ export class CounselingRepositoryImpl implements CounselingRepository {
},
where: { id: +counselingId },
});

if (result === null)
throw new BadRequestException('해당 진료는 존재하지 않습니다.');
return this.mapper.mapEntityToDomain(result);
}

Expand Down

0 comments on commit 20fc554

Please sign in to comment.