Skip to content

Commit

Permalink
Merge branch 'dev' into feat-진석
Browse files Browse the repository at this point in the history
  • Loading branch information
SiWooJinSeok committed Apr 25, 2024
2 parents 5c2d3f5 + 869680d commit bedc8ef
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 9 deletions.
4 changes: 2 additions & 2 deletions src/common/logger/logger.config.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import * as winston from 'winston';
import moment from 'moment-timezone';
import appRoot from 'app-root-path';
import appRootPath from 'app-root-path';

export const appendTimestamp = winston.format((info, opts) => {
if (opts.tz) {
Expand All @@ -14,7 +14,7 @@ export const dailyOptions = (level: string) => {
return {
level: 'info',
datePattern: 'YYYY-MM-DD', // 날짜 포맷
dirname: `${appRoot.path}/logs` + `/${level}`, // 저장할 URL: 여기서는 루트에 logs라는 폴더가 생기고 그 아래에 level 폴더
dirname: `${appRootPath.path}/logs` + `/${level}`, // 저장할 URL: 여기서는 루트에 logs라는 폴더가 생기고 그 아래에 level 폴더
filename: `%DATE%.${level}.log`,
maxFiles: 20, // 보관할 최대 로그 수
zippedArchive: true, // 로그가 쌓였을 때 압축
Expand Down
35 changes: 28 additions & 7 deletions src/common/logger/logger.middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,19 +3,40 @@ import { Request, Response, NextFunction } from 'express';

@Injectable()
export class LoggingMiddleware implements NestMiddleware {
private logger = new Logger('HTTP'); //HTTP 로그를 기록하는 logger 프로퍼티를 선언
private logger = new Logger('HTTP');

use(req: Request, res: Response, next: NextFunction) {
//미들웨어 로직을 정의
const { ip, method, originalUrl } = req; //IP 주소, HTTP 메서드 및 원본 URL을 추출
const { ip, method, originalUrl } = req;
const userAgent = req.get('user-agent') || '';
res.on('finish', () => {
//로깅 상세설정
const reqHeaders = JSON.stringify(req.headers);
const reqBody = JSON.stringify(req.body);

const chunks: Buffer[] = [];

const originalWrite = res.write.bind(res);
res.write = (...args: any[]) => {
chunks.push(Buffer.from(args[0]));
return originalWrite(...args);
};

const originalEnd = res.end.bind(res);
res.end = (...args: any[]) => {
if (args[0]) {
chunks.push(Buffer.from(args[0]));
}
const responseBody = Buffer.concat(chunks).toString('utf-8');
const resHeaders = JSON.stringify(res.getHeaders());

const { statusCode, statusMessage } = res;
const logLevel = statusCode >= 400 ? 'error' : 'log';

this.logger[logLevel](
`Request from ${ip} to ${method} ${originalUrl} - ${statusCode} ${statusMessage} - ${userAgent}`,
`Request from ${ip} to ${method} ${originalUrl} - ${statusCode} ${statusMessage} - ${userAgent} \nReq Headers: ${reqHeaders} \nReq Body: ${reqBody} \nRes Headers: ${resHeaders} \nRes Body: ${responseBody}`,
);
});

return originalEnd(...args);
};

next();
}
}

0 comments on commit bedc8ef

Please sign in to comment.