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

Be/task/logger #215

Merged
merged 21 commits into from
Dec 6, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
19b2ac8
swagger 설정
twoo1999 Nov 13, 2023
652388e
resolve conflict
twoo1999 Nov 20, 2023
fbadd4a
Merge branch 'BE/release' of https://github.com/boostcampwm2023/iOS01…
twoo1999 Nov 22, 2023
3291df8
Merge branch 'BE/release' of https://github.com/boostcampwm2023/iOS01…
twoo1999 Nov 23, 2023
498ac06
Merge branch 'BE/release' of https://github.com/boostcampwm2023/iOS01…
twoo1999 Nov 23, 2023
7a8404e
Merge branch 'BE/release' of https://github.com/boostcampwm2023/iOS01…
twoo1999 Nov 25, 2023
9027029
Merge branch 'BE/release' of https://github.com/boostcampwm2023/iOS01…
twoo1999 Nov 25, 2023
f118716
Merge branch 'BE/release' of https://github.com/boostcampwm2023/iOS01…
twoo1999 Nov 25, 2023
536fd52
Merge branch 'BE/release' of https://github.com/boostcampwm2023/iOS01…
twoo1999 Nov 28, 2023
cfe9dfe
Merge branch 'BE/release' of https://github.com/boostcampwm2023/iOS01…
twoo1999 Nov 30, 2023
6fc52ce
Merge branch 'BE/release' of https://github.com/boostcampwm2023/iOS01…
twoo1999 Nov 30, 2023
3005447
Merge branch 'BE/release' of https://github.com/boostcampwm2023/iOS01…
twoo1999 Dec 3, 2023
98bf7e1
Merge branch 'BE/release' of https://github.com/boostcampwm2023/iOS01…
twoo1999 Dec 5, 2023
a1e470f
Merge branch 'BE/release' of https://github.com/boostcampwm2023/iOS01…
twoo1999 Dec 6, 2023
d576197
:recycle: S3 객체 추상화
twoo1999 Dec 6, 2023
d40d555
:sparkles: Spot 기록 시 이미지 저장 실패 에러 처리
twoo1999 Dec 6, 2023
63b7ab7
:recycle: 의미없는 부분 수정
twoo1999 Dec 6, 2023
be821c2
:recycle: 스팟 기록 요청 및 응답 객체 생성
twoo1999 Dec 6, 2023
425d7fa
:recycle: 이미지 저장 시 url이 아닌 key로 저장
twoo1999 Dec 6, 2023
bd5df9b
:recycle: S3 객체 추상화 및 비지니스 로직 수정
twoo1999 Dec 6, 2023
ca2abb5
:sparkles: Logger 설정
twoo1999 Dec 6, 2023
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
9 changes: 7 additions & 2 deletions BE/musicspot/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 } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { MongooseModule } from '@nestjs/mongoose';
Expand All @@ -7,6 +7,7 @@ import { SpotModule } from './spot/module/spot.module';
import { UserModule } from './user/module/user.module';

import { ReleaseController } from './releasePage/release.controller';
import { LoggerMiddleware } from './common/middleware/logger.middleware';

@Module({
imports: [
Expand All @@ -20,4 +21,8 @@ import { ReleaseController } from './releasePage/release.controller';
controllers: [AppController, ReleaseController],
providers: [AppService],
})
export class AppModule {}
export class AppModule {
configure(consumer: MiddlewareConsumer) {
consumer.apply(LoggerMiddleware).forRoutes('/*');
}
}
57 changes: 28 additions & 29 deletions BE/musicspot/src/common/logger/winston.util.ts
Original file line number Diff line number Diff line change
@@ -1,30 +1,29 @@
import { utilities, WinstonModule } from 'nest-winston';
import * as winstonDaily from 'winston-daily-rotate-file';
import * as winston from 'winston';

// import { utilities, WinstonModule } from 'nest-winston';
// import * as winstonDaily from 'winston-daily-rotate-file';
// import * as winston from 'winston';

// const logDir = `${__dirname}/../../logs`;
// const options = (level: string) => {
// return {
// level,
// datePattern: 'YYYY-MM-DD',
// dirname: logDir + `/${level}`,
// filename: `%DATE%.${level}.log`,
// maxFiles: 30,
// zippedArchive: true,
// };
// };
// export const winstonLogger = WinstonModule.createLogger({
// transports: [
// new winston.transports.Console({
// level: 'silly',
// format: winston.format.combine(
// winston.format.timestamp(),
// utilities.format.nestLike('music-spot', { prettyPrint: true }),
// ),
// }),
// new winstonDaily(options('info')),
// new winstonDaily(options('warn')),
// new winstonDaily(options('error')),
// ],
// });
const logDir = `${__dirname}/../../logs`;
const options = (level: string) => {
return {
level,
datePattern: 'YYYY-MM-DD',
dirname: logDir + `/${level}`,
filename: `%DATE%.${level}.log`,
maxFiles: 30,
zippedArchive: true,
};
};
export const winstonLogger = WinstonModule.createLogger({
transports: [
new winston.transports.Console({
level: 'silly',
format: winston.format.combine(
winston.format.timestamp(),
utilities.format.nestLike('music-spot', { prettyPrint: true }),
),
}),
new winstonDaily(options('info')),
new winstonDaily(options('warn')),
new winstonDaily(options('error')),
],
});
61 changes: 38 additions & 23 deletions BE/musicspot/src/common/middleware/logger.middleware.ts
Original file line number Diff line number Diff line change
@@ -1,26 +1,41 @@
// import { Injectable, NestMiddleware } from '@nestjs/common';
// import { Response, Request, NextFunction } from 'express';
// import { winstonLogger } from '../logger/winston.util';
import { Injectable, NestMiddleware } from '@nestjs/common';
import { Response, Request, NextFunction } from 'express';
import { winstonLogger } from '../logger/winston.util';

// @Injectable()
// export class LoggerMiddleware implements NestMiddleware {
// constructor() {}
@Injectable()
export class LoggerMiddleware implements NestMiddleware {
use(req: Request, res: Response, next: NextFunction) {
const { ip, method, originalUrl } = req;
res.on('finish', () => {
const { statusCode } = res;

// use(req: Request, res: Response, next: NextFunction) {
// const { ip, method, originalUrl } = req;
if (statusCode >= 400 && statusCode < 500) {
winstonLogger.warn(
`[${method}]${originalUrl}(${statusCode}) ${ip} Reqbody:${JSON.stringify(
req.body,
null,
2,
)}`,
);
} else if (statusCode >= 500) {
winstonLogger.error(
`[${method}]${originalUrl}(${statusCode}) ${ip} Reqbody:${JSON.stringify(
req.body,
null,
2,
)}`,
);
} else {
winstonLogger.warn(
`[${method}]${originalUrl}(${statusCode}) ${ip} Reqbody:${JSON.stringify(
req.body,
null,
2,
)}`,
);
}
});

// res.on('finish', () => {
// const { statusCode } = res;
// console.log(statusCode);
// // if (statusCode >= 400 && statusCode < 500) {
// // winstonLogger.warn(`[${method}]${originalUrl}(${statusCode}) ${ip}`);
// // console.log('ASDS');
// // } else if (statusCode >= 500) {
// // winstonLogger.error(`[${method}]${originalUrl}(${statusCode}) ${ip}`);
// // }
// winstonLogger.warn(`[${method}]${originalUrl}(${statusCode}) ${ip}`);
// });

// next();
// }
// }
next();
}
}
41 changes: 41 additions & 0 deletions BE/musicspot/src/common/s3/objectStorage.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import * as AWS from 'aws-sdk';
import * as dotenv from 'dotenv';
dotenv.config();

interface INcloudStorageConfig {
endpoint: string;
region: string;
accessKey: string;
secretKey: string;
bucketName: string;
}

class NcloudStorageConfig implements INcloudStorageConfig {
endpoint: string;
region: string;
accessKey: string;
secretKey: string;
bucketName: string;
constructor() {
this.endpoint = process.env.NCLOUD_ENDPOINT;
this.region = process.env.NCLOUD_REGION;
this.accessKey = process.env.NCLOUD_ACCESS_KEY;
this.secretKey = process.env.NCLOUD_SECRET_KEY;
this.bucketName = process.env.BUCKET_NAME;
}

getConfig() {
return {
endpoint: this.endpoint,
region: this.region,
credentials: {
accessKeyId: this.accessKey,
secretAccessKey: this.secretKey,
},
};
}
}

export const S3 = new AWS.S3(new NcloudStorageConfig().getConfig());
export const bucketName = process.env.BUCKET_NAME;
export const endpoint = process.env.NCLOUD_ENDPOINT;
6 changes: 3 additions & 3 deletions BE/musicspot/src/filters/exception.enum.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,13 @@ export enum JourneyExceptionMessageEnum {
}

export enum SpotExceptionCodeEnum {
SpotNotFound = '0003',
UnexpectedError = '9997',
SpotNotFound = '0020',
SpotRecordFail = '0021',
}

export enum SpotExceptionMessageEnum {
SpotNotFound = 'SpotId에 해당하는 Spot이 없습니다.',
UnexpectedError = '예상치 못한 오류입니다.',
SpotRecordFail = 'Spot 이미지 저장 중 에러가 발생했습니다.',
}

export enum UserExceptionMessageEnum {
Expand Down
10 changes: 10 additions & 0 deletions BE/musicspot/src/filters/spot.exception.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,3 +11,13 @@ export class SpotNotFoundException extends BaseException {
this.message = SpotExceptionMessageEnum.SpotNotFound;
}
}

export class SpotRecordFail extends BaseException {
constructor() {
super(
SpotExceptionCodeEnum.SpotRecordFail,
HttpStatus.INTERNAL_SERVER_ERROR,
);
this.message = SpotExceptionMessageEnum.SpotRecordFail;
}
}
2 changes: 2 additions & 0 deletions BE/musicspot/src/journey/controller/journey.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ import {
ValidationPipe,
Get,
Query,
Res,
Req,
} from '@nestjs/common';
import { JourneyService } from '../service/journey.service';

Expand Down
7 changes: 2 additions & 5 deletions BE/musicspot/src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,10 @@ import { AppModule } from './app.module';
import { ValidationPipe } from '@nestjs/common';
import { NestExpressApplication } from '@nestjs/platform-express';
import { AllExceptionFilter } from './filters/exception.filter';

// import { winstonLogger } from './common/logger/winston.util';
import { winstonLogger } from './common/logger/winston.util';
async function bootstrap() {
const app = await NestFactory.create<NestExpressApplication>(AppModule, {
// logger: winstonLogger,
const app = await NestFactory.create<NestExpressApplication>(AppModule);

});
const config = new DocumentBuilder()
.setTitle('Music Spot') // 문서의 제목
.setDescription('iOS01 Music Spot App API') // 문서의 간단한 설명
Expand Down
6 changes: 3 additions & 3 deletions BE/musicspot/src/spot/controller/spot.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import {
Query,
} from '@nestjs/common';
import { ApiCreatedResponse, ApiOperation, ApiTags } from '@nestjs/swagger';
import { RecordSpotDTO } from '../dto/recordSpot.dto';
import { RecordSpotReqDTO } from '../dto/recordSpot.dto';
import { SpotService } from '../service/spot.service';
import { FileInterceptor } from '@nestjs/platform-express';
import { Spot } from '../schema/spot.schema';
Expand All @@ -26,10 +26,10 @@ export class SpotController {
type: Spot,
})
@UseInterceptors(FileInterceptor('image'))
@Post('create')
@Post('')
async create(
@UploadedFile() file: Express.Multer.File,
@Body() recordSpotDTO: RecordSpotDTO,
@Body() recordSpotDTO: RecordSpotReqDTO,
) {
return await this.spotService.create(file, recordSpotDTO);
}
Expand Down
41 changes: 39 additions & 2 deletions BE/musicspot/src/spot/dto/recordSpot.dto.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { ApiProperty } from '@nestjs/swagger';
import { IsDateString, IsString } from 'class-validator';
import { IsDateString, IsString, IsUrl } from 'class-validator';
import { IsCoordinate } from '../../common/decorator/coordinate.decorator';

export class RecordSpotDTO {
export class RecordSpotReqDTO {
@ApiProperty({
example: '655efda2fdc81cae36d20650',
description: '여정 id',
Expand Down Expand Up @@ -36,3 +36,40 @@ export class RecordSpotDTO {
// })
// readonly photoData: Buffer;
}

export class RecordSpotResDTO {
@ApiProperty({
example: '655efda2fdc81cae36d20650',
description: '여정 id',
required: true,
})
@IsString()
readonly journeyId: string;

@ApiProperty({
example: [37.555946, 126.972384],
description: '위치 좌표',
required: true,
})
@IsCoordinate({
message: '배열의 각 요소는 양수여야 하고 두 개의 요소만 허용됩니다.',
})
readonly coordinate: number[];

@ApiProperty({
example: '2023-11-22T12:00:00Z',
description: 'timestamp',
required: true,
})
@IsDateString()
readonly timestamp: string;

@ApiProperty({
example:
'https://music-spot-storage.kr.object.ncloudstorage.com/path/name?AWSAccessKeyId=key&Expires=1701850233&Signature=signature',
description: 'presigned url',
required: true,
})
@IsUrl()
readonly photo: string;
}
2 changes: 1 addition & 1 deletion BE/musicspot/src/spot/schema/spot.schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ export class Spot {
required: true,
})
@Prop({ type: String })
photoUrl: string;
photoKey: string;
}

export const SpotSchema = SchemaFactory.createForClass(Spot);
Loading