Skip to content

Commit

Permalink
Chore: 로그 메세지 수정
Browse files Browse the repository at this point in the history
  • Loading branch information
Jnnsu committed Apr 25, 2024
1 parent 869680d commit dfcc27a
Show file tree
Hide file tree
Showing 9 changed files with 27 additions and 14 deletions.
2 changes: 1 addition & 1 deletion src/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import { LoggingMiddleware } from './common/logger/logger.middleware';
imports: [
LoggerModule,
AuthModule,
ConfigModule.forRoot({ isGlobal: true, envFilePath: '.env' }),
ConfigModule.forRoot({ isGlobal: true }),
FriendModule,
],
controllers: [UserController, AppController],
Expand Down
2 changes: 1 addition & 1 deletion src/auth/auth.controller.spec.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import { ConfigModule } from '@nestjs/config';
import { Test, TestingModule } from '@nestjs/testing';
import { AuthController } from './auth.controller';
import { AuthService } from './auth.service';
import { PrismaService } from '../prisma.service';
import { UserService } from '../user/user.service';
import { ConfigModule } from '@nestjs/config';
import { LoggerModule } from '../common/logger/logger.module';

describe('AuthController', () => {
Expand Down
2 changes: 0 additions & 2 deletions src/auth/auth.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,8 @@ import { AuthController } from './auth.controller';
import { AuthService } from './auth.service';
import { UserService } from '../user/user.service';
import { PrismaService } from '../prisma.service';
import { LoggerModule } from 'src/common/logger/logger.module';

@Module({
imports: [LoggerModule],
controllers: [AuthController, PasswordController],
providers: [AuthService, UserService, PrismaService],
})
Expand Down
2 changes: 1 addition & 1 deletion src/auth/auth.service.spec.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { ConfigModule } from '@nestjs/config';
import { Test, TestingModule } from '@nestjs/testing';
import { AuthService } from './auth.service';
import { PrismaService } from '../prisma.service';
import { UserService } from '../user/user.service';
import { ConfigModule } from '@nestjs/config';
import { LoggerModule } from '../common/logger/logger.module';

describe('AuthService', () => {
Expand Down
4 changes: 2 additions & 2 deletions src/auth/auth.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,14 @@ import { EmailDto } from './../dto/email.dto';
import { ForgotPasswordDto } from './../dto/forgotPassword.dto';
import { ChangePasswordDto } from './../dto/changePassword.dto';
import { Logger } from 'winston';
import { WINSTON_MODULE_PROVIDER } from 'nest-winston';
import { WINSTON_MODULE_NEST_PROVIDER } from 'nest-winston';

@Injectable()
export class AuthService {
private readonly cognitoClient: CognitoIdentityServiceProvider;
private readonly clientId: string;
constructor(
@Inject(WINSTON_MODULE_PROVIDER) private readonly logger: Logger,
@Inject(WINSTON_MODULE_NEST_PROVIDER) private readonly logger: Logger,
private readonly configService: ConfigService,
private readonly userService: UserService,
) {
Expand Down
2 changes: 1 addition & 1 deletion src/common/logger/logger.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ export const appendTimestamp = winston.format((info, opts) => {
// 로그 저장 파일 옵션
export const dailyOptions = (level: string) => {
return {
level: 'info',
level: level,
datePattern: 'YYYY-MM-DD', // 날짜 포맷
dirname: `${appRootPath.path}/logs` + `/${level}`, // 저장할 URL: 여기서는 루트에 logs라는 폴더가 생기고 그 아래에 level 폴더
filename: `%DATE%.${level}.log`,
Expand Down
19 changes: 15 additions & 4 deletions src/common/logger/logger.middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@ export class LoggingMiddleware implements NestMiddleware {
use(req: Request, res: Response, next: NextFunction) {
const { ip, method, originalUrl } = req;
const userAgent = req.get('user-agent') || '';
const reqHeaders = JSON.stringify(req.headers);
const reqBody = JSON.stringify(req.body);
const reqHeaders = JSON.stringify(req.headers, null, 2);
const reqBody = JSON.stringify(req.body, null, 2);

const chunks: Buffer[] = [];

Expand All @@ -25,13 +25,24 @@ export class LoggingMiddleware implements NestMiddleware {
chunks.push(Buffer.from(args[0]));
}
const responseBody = Buffer.concat(chunks).toString('utf-8');
const resHeaders = JSON.stringify(res.getHeaders());
const resHeaders = JSON.stringify(res.getHeaders(), null, 2);

const { statusCode, statusMessage } = res;
const logLevel = statusCode >= 400 ? 'error' : 'log';
const levelColor =
statusCode >= 400
? '🟥🟥🟥🟥🟥🟥🟥🟥🟥🟥'
: statusCode >= 300
? '🟧🟧🟧🟧🟧🟧🟧🟧🟧🟧'
: '🟩🟩🟩🟩🟩🟩🟩🟩🟩🟩';

this.logger[logLevel](
`Request from ${ip} to ${method} ${originalUrl} - ${statusCode} ${statusMessage} - ${userAgent} \nReq Headers: ${reqHeaders} \nReq Body: ${reqBody} \nRes Headers: ${resHeaders} \nRes Body: ${responseBody}`,
`Request from ${ip} to ${method} ${originalUrl} - ${statusCode} ${statusMessage} - ${userAgent}\n\n` +
`${levelColor}\n` +
`👩 Req Headers:\n${reqHeaders}\n\n` +
`👚 Req Body:\n${reqBody}\n\n` +
`👨 Res Headers:\n${resHeaders}\n\n` +
`👕 Res Body:\n${responseBody}\n`,
);

return originalEnd(...args);
Expand Down
2 changes: 1 addition & 1 deletion src/common/logger/logger.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ import { dailyOptions } from './logger.config';
),
}),

new winstonDaily(dailyOptions('warn')),
new winstonDaily(dailyOptions('info')),
new winstonDaily(dailyOptions('error')),
new winstonDaily(dailyOptions('fatal')),
],
Expand Down
6 changes: 5 additions & 1 deletion src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,12 @@ import { NestFactory } from '@nestjs/core';
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';
import { AppModule } from './app.module';
import { ValidationPipe } from '@nestjs/common';
import { WINSTON_MODULE_NEST_PROVIDER } from 'nest-winston';

async function bootstrap() {
const app = await NestFactory.create(AppModule);
const app = await NestFactory.create(AppModule, { bufferLogs: true });
const logger = app.get(WINSTON_MODULE_NEST_PROVIDER);
app.useLogger(logger);

app.useGlobalPipes(
new ValidationPipe({
Expand All @@ -27,5 +30,6 @@ async function bootstrap() {
});

await app.listen(80);
logger.log('Application is listening on port 80');
}
bootstrap();

0 comments on commit dfcc27a

Please sign in to comment.