Skip to content

Commit

Permalink
Merge pull request #46 from mash-up-kr/feature/simple-log-for-prod
Browse files Browse the repository at this point in the history
feat: production 환경에서는 로그를 간결하게 남기도록 한다.
  • Loading branch information
seohyun0120 authored Sep 21, 2024
2 parents d6beb14 + c6fd737 commit f361981
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 10 deletions.
3 changes: 3 additions & 0 deletions src/util/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,10 @@ const FCM_PROJECT_ID = process.env.FCM_PROJECT_ID;
const FCM_PRIVATE_KEY = process.env.FCM_PRIVATE_KEY;
const FCM_CLIENT_EMAIL = process.env.FCM_CLIENT_EMAIL;

const ENV = process.env.NODE_ENV;

export default {
ENV,
DB_URL,
PORT,
AWS_ACCESS_KEY_ID,
Expand Down
33 changes: 23 additions & 10 deletions src/util/logger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ import { randomUUID } from 'crypto';
import { Request, Response, NextFunction } from 'express';
import pino from 'pino';

import config from './config';

const transport = pino.transport({
targets: [
{
Expand All @@ -20,24 +22,35 @@ const attachRequestId = (req: Request, res: Response, next: NextFunction) => {
next();
};

const ENV = `${config.ENV}`;
const isProduction = ENV === 'production';
logger.info(`env: ${ENV} - ${isProduction}`);

const loggerMiddleware = (req: Request, res: Response, next: NextFunction) => {
const start = Date.now();
const startTime = Date.now();
const { method, originalUrl, body } = req;

logger.info(
{ method: req.method, url: req.originalUrl, body: req.body },
`--> [${req.method}] ${req.originalUrl} Request called`,
isProduction ? undefined : { method, url: originalUrl, body },
`--> ${method} ${originalUrl}`,
);

const originalSend = res.send;
res.send = (data) => {
logger[res.statusCode !== 200 ? 'error' : 'info'](
{
statusCode: res.statusCode,
duration: `${Date.now() - start}ms`,
response: JSON.parse(data),
},
`<-- [${req.method}] ${res.statusCode} ${req.originalUrl} Response received in ${Date.now() - start}ms`,
const duration = Date.now() - startTime;
const statusCode = res.statusCode;

logger[statusCode !== 200 ? 'error' : 'info'](
isProduction
? undefined
: {
method,
url: originalUrl,
response: JSON.parse(data),
},
`<-- ${statusCode} ${method} ${originalUrl} (${duration}ms)`,
);

return originalSend.bind(res)(data);
};

Expand Down

0 comments on commit f361981

Please sign in to comment.