Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: production 환경에서는 로그를 간결하게 남기도록 한다. #46

Merged
merged 1 commit into from
Sep 21, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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