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

Logger 도입 #95

Merged
merged 6 commits into from
Sep 25, 2023
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
12 changes: 10 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 { ConfigModule, ConfigService } from '@nestjs/config';
import { MongooseModule } from '@nestjs/mongoose';
import { AppController } from './app.controller';
Expand All @@ -9,6 +9,8 @@ import { CommitModule } from './commit/commit.module';
import { JwtModule, JwtService } from '@nestjs/jwt';
import { NotificationModule } from './notification/notification.module';
import { ViewModule } from './view/view.module';
import { LoggerModule } from './logger/logger.module';
import { LoggerMiddleware } from './logger/logger.middleware';

@Module({
imports: [
Expand Down Expand Up @@ -36,9 +38,15 @@ import { ViewModule } from './view/view.module';
UserModule,
NotificationModule,
ViewModule,
LoggerModule
],

controllers: [AppController],
providers: [AppService, JwtService],
})
export class AppModule {}

export class AppModule implements NestModule {
configure(consumer: MiddlewareConsumer) {
consumer.apply(LoggerMiddleware).forRoutes('*')
}
}
5 changes: 4 additions & 1 deletion src/app.service.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
import { Injectable } from '@nestjs/common';
import { Injectable, Logger } from '@nestjs/common';

@Injectable()
export class AppService {
private readonly logger = new Logger(AppService.name);

getHello(): string {
this.logger.debug("Hello TwoToo!");
return 'Hello TwoToo!';
}
}
4 changes: 4 additions & 0 deletions src/httpException.filter.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,19 @@
import { ExceptionFilter, Catch, ArgumentsHost, HttpException } from '@nestjs/common';
import { Request, Response } from 'express';
import { LoggerService } from './logger/logger.service';

@Catch(Error)
export class HttpExceptionFilter implements ExceptionFilter {
constructor(private readonly logger: LoggerService) { }
catch(exception: HttpException, host: ArgumentsHost) {
const ctx = host.switchToHttp();
const response = ctx.getResponse<Response>();
const request = ctx.getRequest<Request>();
const status = exception.getStatus ? exception.getStatus() : 500;

const message = exception['response'] ? exception['response'].message : exception.message;
this.logger.error(`${request.method} ${status} - ${message} - ${request.url}`);

response.status(status).json({
message: message,
statusCode: status,
Expand Down
21 changes: 21 additions & 0 deletions src/logger/logger.middleware.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { Logger, NestMiddleware } from '@nestjs/common';
import { Request, Response, NextFunction } from 'express';

export class LoggerMiddleware implements NestMiddleware {
private logger = new Logger();
use(req: Request, res: Response, next: NextFunction) {
const startAt = process.hrtime();
const { method, originalUrl } = req;
this.logger.log(`${method} --> ${originalUrl}`);

res.on('finish', () => {
const { statusCode } = res;
const diff = process.hrtime(startAt);
const responseTime = Math.round(diff[0] * 1e3 + diff[1] * 1e-6);
this.logger.log(
`${method} ${statusCode} ${responseTime}ms <-- ${originalUrl}`,
);
});
next();
}
}
8 changes: 8 additions & 0 deletions src/logger/logger.module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { Module } from "@nestjs/common";
import { LoggerService } from "./logger.service";

@Module({
providers: [LoggerService],
exports: [LoggerService],
})
export class LoggerModule {}
20 changes: 20 additions & 0 deletions src/logger/logger.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { Injectable, LoggerService as NestLoggerService } from "@nestjs/common";

@Injectable()
export class LoggerService implements NestLoggerService {
debug(message: any, ...optionalParams: any[]) {
console.debug(`[debug] ${message}`, ...optionalParams);
}

warn(message: any, ...optionalParams: any[]) {
console.warn(`[warn] ${message}`, ...optionalParams);
}

log(message: any, ...optionalParams: any[]) {
console.log(`[log] ${message}`, ...optionalParams);
}

error(message: any, ...optionalParams: any[]) {
console.error(`[error] ${message}`, ...optionalParams);
}
}
6 changes: 4 additions & 2 deletions src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,11 @@ import { AppModule } from './app.module';
import { setupSwagger } from './swagger';
import { HttpExceptionFilter } from './httpException.filter';
import { ValidationPipe } from '@nestjs/common';
import { LoggerService } from './logger/logger.service';

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

const configService: ConfigService = app.get(ConfigService);

Expand All @@ -23,7 +25,7 @@ async function bootstrap() {
});

setupSwagger(app);
app.useGlobalFilters(new HttpExceptionFilter());
app.useGlobalFilters(new HttpExceptionFilter(app.get(LoggerService)));
app.useGlobalPipes(new ValidationPipe());
await app.listen(3000);
}
Expand Down
5 changes: 4 additions & 1 deletion src/user/user.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,14 +24,16 @@ import { JwtPayload } from 'src/auth/auth.types';
import { JwtParam } from 'src/auth/auth.user.decorator';
import { AuthGuard } from '../auth/auth.guard';
import { ChallengeService } from 'src/challenge/challenge.service';
import { LoggerService } from 'src/logger/logger.service';

@ApiTags('user')
@Controller('user')
export class UserController {
constructor(
private readonly userSvc: UserService,
private readonly challengeSvc: ChallengeService,
) {}
private readonly loggerSvc: LoggerService
) { }

@Post('/authorize')
@ApiOperation({
Expand All @@ -50,6 +52,7 @@ export class UserController {
userNo: user.userNo,
deviceToken: deviceToken,
});

return {
state: curState,
accessToken: user.accessToken,
Expand Down
2 changes: 2 additions & 0 deletions src/user/user.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import {
ChallengeCounterSchema,
} from 'src/challenge/schema/challenge-counter.schema';
import { ChallengeModule } from 'src/challenge/challenge.module';
import { LoggerModule } from 'src/logger/logger.module';

@Module({
imports: [
Expand All @@ -22,6 +23,7 @@ import { ChallengeModule } from 'src/challenge/challenge.module';
{ name: ChallengeCounter.name, schema: ChallengeCounterSchema },
]),
forwardRef(() => ChallengeModule),
LoggerModule
],
providers: [UserService, AuthGuard, JwtService],
controllers: [UserController],
Expand Down
21 changes: 17 additions & 4 deletions src/user/user.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import { JwtPayload } from '../auth/auth.types';
import { LoginType } from './user.types';
import { ChallengeService } from '../challenge/challenge.service';
import { UserInfoResDto } from './dto/user.dto';
import { LoggerService } from '../logger/logger.service';

export enum LOGIN_STATE {
NEED_NICKNAME = 'NEED_NICKNAME',
Expand All @@ -36,7 +37,8 @@ export class UserService {
private configService: ConfigService,
@Inject(forwardRef(() => ChallengeService))
private challengeSvc: ChallengeService,
) {}
private logger: LoggerService
) { }

async signUp({
socialId,
Expand All @@ -61,8 +63,9 @@ export class UserService {
accessToken: accessToken,
deviceToken: deviceToken,
});

await user.save();

this.logger.log(`Created user - user(${JSON.stringify(this.getPartialUserInfo(user))}})`);
return user;
}

Expand All @@ -83,6 +86,7 @@ export class UserService {
},
{ new: true },
);
this.logger.debug(`Update user 닉네임 설정 완료`);
} else {
if (data.partnerNo === userNo) {
throw new ConflictException('자기 자신과 파트너 매칭할 수 없습니다.');
Expand Down Expand Up @@ -125,17 +129,19 @@ export class UserService {
]);

updatedUser = await this.getUser(userNo);
this.logger.debug(`Update user 닉네임 설정 및 파트너 매칭 완료`);
} catch (err) {
throw new NotFoundException('파트너 매칭에 실패했습니다.');
}
}

this.logger.log(`Updated user - user(${JSON.stringify(this.getPartialUserInfo(user))}})`);
return updatedUser as User;
}

async checkPartner(userNo: number): Promise<number> {
const user = await this.getUser(userNo);

this.logger.log(`Check partnerNo - userNo(${userNo}), parterNo(${user.partnerNo || 0})`);
return user.partnerNo || 0;
}

Expand All @@ -146,6 +152,7 @@ export class UserService {
throw new NotFoundException('해당 유저가 존재하지 않습니다.');
}

this.logger.log(`Get User - user(${JSON.stringify(this.getPartialUserInfo(user))}})`);
return user;
}

Expand Down Expand Up @@ -232,6 +239,7 @@ export class UserService {
if (partnerNo === null) {
throw new NotFoundException('파트너가 존재하지 않습니다.');
}

try {
await this.userModel.updateMany(
{
Expand All @@ -240,10 +248,13 @@ export class UserService {
{ $set: { nickname: null, partnerNo: null } },
);

this.logger.debug(`Delete Partner - userNo(${user.userNo}) partnerNo(${user.partnerNo})`);

await this.challengeSvc.deleteAllChallenges(user.userNo);
this.logger.log(`Delete all challenges - userNo(${user.userNo})`);
return true;
} catch (e) {
console.log(e);
this.logger.error(e);
return false;
}
}
Expand All @@ -257,6 +268,7 @@ export class UserService {
throw new NotFoundException(`${userNo}의 삭제에 실패했습니다.`);
}

this.logger.log(`Delete User - userNo(${user.userNo})`);
return true;
}

Expand All @@ -274,6 +286,7 @@ export class UserService {
throw new NotFoundException(`${userNo}닉네임 변경에 실패했습니다.`);
}

this.logger.log(`Changer User nickname - user(${JSON.stringify(this.getPartialUserInfo(user))}})`);
return {
userNo: user.userNo,
nickname: user.nickname,
Expand Down