-
Notifications
You must be signed in to change notification settings - Fork 2
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] logger 적용 #333
Merged
+576
−18
Merged
[Feat] logger 적용 #333
Changes from 8 commits
Commits
Show all changes
14 commits
Select commit
Hold shift + click to select a range
3e5bd80
refactor: 패키지 구조 변경
Fixtar da7fafc
feat: winston logger 구현
Fixtar ae8239e
feat: log ObjcetStorage로 업로드 기능 추가
Fixtar c4e876f
fix: batch 단위 수정
Fixtar 785c71b
fix: 로그에 결과값 포함
Fixtar 46f71bc
fix: 주석 제거
Fixtar 78d062e
fix: singleton 으로 logger사용
Fixtar eeefb25
fix: console.log 제거
Fixtar aceac7e
fix: conflict해결
Fixtar 8c8c792
fix: merge develop
Fixtar 5244322
fix: 사용하지 않는 Import 제거
Fixtar d344eb3
fix: pnpm Install 다시 진행
Fixtar 525194c
fix: s3 sdk 버전 통합
Fixtar ec2bdbb
Merge branch 'develop' into feat/#304/winston
Fixtar File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
File renamed without changes.
File renamed without changes.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,33 @@ | ||
import path from 'path'; | ||
|
||
import { Injectable } from '@nestjs/common'; | ||
import { Cron, CronExpression } from '@nestjs/schedule'; | ||
|
||
import { LoggerService } from './logger.service'; | ||
import { NcpService } from '../ncp/ncp.service'; | ||
|
||
@Injectable() | ||
export class LogBatchService { | ||
constructor( | ||
private readonly ncpService: NcpService, | ||
private readonly loggerService: LoggerService | ||
) {} | ||
|
||
@Cron(CronExpression.EVERY_DAY_AT_1AM) | ||
async uploadLogToObjectStorage() { | ||
const logsDir = path.join(__dirname, '../../../logs'); | ||
const today = new Date(); | ||
today.setHours(today.getHours() + 9); | ||
today.setDate(today.getDate() - 1); | ||
|
||
const logFileName = `application-${today.toISOString().split('T')[0]}.log`; | ||
const localFilePath = path.join(logsDir, logFileName); | ||
try { | ||
const remoteFileName = `logs/${logFileName}`; | ||
const result = await this.ncpService.uploadFile(localFilePath, remoteFileName); | ||
this.loggerService.log(`Log file uploaded successfully: ${result}`, 'logBatchService'); | ||
} catch (error) { | ||
this.loggerService.log(`Failed to upload log file: ${error}`, 'logBatchService'); | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,26 @@ | ||
import { Injectable, NestMiddleware } from '@nestjs/common'; | ||
import { Request, Response, NextFunction } from 'express'; | ||
|
||
import { LoggerService } from './logger.service'; | ||
|
||
@Injectable() | ||
export class LoggerMiddleware implements NestMiddleware { | ||
constructor(private readonly logger: LoggerService) {} | ||
|
||
use(req: Request, res: Response, next: NextFunction) { | ||
const { method, originalUrl } = req; | ||
const userAgent = req.headers['user-agent'] || 'Unknown'; | ||
|
||
res.on('finish', () => { | ||
const { statusCode } = res; | ||
const contentLength = res.get('content-length') || 0; | ||
|
||
this.logger.log( | ||
`[${method}] ${originalUrl} - ${statusCode} - ${contentLength} bytes - UserAgent: ${userAgent}`, | ||
'HTTP' | ||
); | ||
}); | ||
|
||
next(); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,17 @@ | ||
import { Global, Module } from '@nestjs/common'; | ||
import { ScheduleModule } from '@nestjs/schedule'; | ||
import { WinstonModule } from 'nest-winston'; | ||
|
||
import { WinstonConfig } from '@/config/winston.confing'; | ||
|
||
import { LogBatchService } from './logger.batch'; | ||
import { LoggerService } from './logger.service'; | ||
import { NcpModule } from '../ncp/ncp.module'; | ||
|
||
@Global() | ||
@Module({ | ||
imports: [WinstonModule.forRoot(WinstonConfig), ScheduleModule.forRoot(), NcpModule], | ||
providers: [LoggerService, LogBatchService], | ||
exports: [LoggerService], | ||
}) | ||
export class LoggerModule {} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,28 @@ | ||
import { Inject, Injectable, LoggerService as NestLoggerService } from '@nestjs/common'; | ||
import { WINSTON_MODULE_PROVIDER } from 'nest-winston'; | ||
import { Logger } from 'winston'; | ||
|
||
@Injectable() | ||
export class LoggerService implements NestLoggerService { | ||
constructor(@Inject(WINSTON_MODULE_PROVIDER) private readonly logger: Logger) {} | ||
|
||
log(message: string, context: string) { | ||
this.logger.info(message, { context }); | ||
} | ||
|
||
error(message: string, trace: string, context: string) { | ||
this.logger.error(message, { trace, context }); | ||
} | ||
|
||
warn(message: string, context: string) { | ||
this.logger.warn(message, { context }); | ||
} | ||
|
||
debug(message: string, context: string) { | ||
this.logger.debug(message, { context }); | ||
} | ||
|
||
verbose(message: string, context: string) { | ||
this.logger.verbose(message, { context }); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,11 @@ | ||
import { Module } from '@nestjs/common'; | ||
|
||
import { NcpConfig } from '@/config/ncp.config'; | ||
|
||
import { NcpService } from './ncp.service'; | ||
|
||
@Module({ | ||
providers: [NcpService, NcpConfig], | ||
exports: [NcpService], | ||
}) | ||
export class NcpModule {} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,40 @@ | ||
import * as fs from 'fs'; | ||
|
||
import { S3Client, PutObjectCommand } from '@aws-sdk/client-s3'; | ||
import { Injectable } from '@nestjs/common'; | ||
import { ConfigService } from '@nestjs/config'; | ||
import { ErrorMessage } from '@repo/types'; | ||
|
||
import { NcpConfig } from '@/config/ncp.config'; | ||
|
||
@Injectable() | ||
export class NcpService { | ||
private s3: S3Client; | ||
|
||
constructor( | ||
private ncpConfig: NcpConfig, | ||
private configService: ConfigService | ||
) { | ||
this.s3 = ncpConfig.s3Client; | ||
} | ||
|
||
async uploadFile(localFilePath: string, remoteFileName: string): Promise<string> { | ||
const bucketName = this.configService.get<string>('NCP_OBJECT_STORAGE_BUCKET'); | ||
const endpoint = this.configService.get<string>('NCP_OBJECT_STORAGE_ENDPOINT'); | ||
|
||
const fileStream = fs.createReadStream(localFilePath); | ||
const params = { | ||
Bucket: bucketName, | ||
Key: remoteFileName, | ||
Body: fileStream, | ||
}; | ||
|
||
try { | ||
const uploadResponse = await this.s3.send(new PutObjectCommand(params)); | ||
const url = `${endpoint}/${bucketName}/${remoteFileName}`; | ||
return remoteFileName; | ||
} catch (error) { | ||
throw new Error(ErrorMessage.FILE_UPLOAD_FAILED); | ||
} | ||
} | ||
} |
File renamed without changes.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,25 @@ | ||
import { S3Client } from '@aws-sdk/client-s3'; | ||
import { Injectable } from '@nestjs/common'; | ||
import { ConfigService } from '@nestjs/config'; | ||
|
||
@Injectable() | ||
export class NcpConfig { | ||
s3Client: S3Client; | ||
|
||
constructor(private configService: ConfigService) { | ||
const accessKeyId = this.configService.get<string>('NCP_ACCESS_KEY'); | ||
const secretAccessKey = this.configService.get<string>('NCP_SECRET_KEY'); | ||
const region = this.configService.get<string>('NCP_OBJECT_STORAGE_REGION'); | ||
const endpoint = this.configService.get<string>('NCP_OBJECT_STORAGE_ENDPOINT'); | ||
|
||
this.s3Client = new S3Client({ | ||
region: region, | ||
credentials: { | ||
accessKeyId: accessKeyId, | ||
secretAccessKey: secretAccessKey, | ||
}, | ||
endpoint: endpoint, | ||
forcePathStyle: true, | ||
}); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,26 @@ | ||
import path from 'path'; | ||
|
||
import * as winston from 'winston'; | ||
import 'winston-daily-rotate-file'; | ||
|
||
export const WinstonConfig = { | ||
transports: [ | ||
new winston.transports.Console({ | ||
format: winston.format.combine( | ||
winston.format.timestamp(), | ||
winston.format.colorize(), | ||
winston.format.printf(({ level, message, timestamp }) => { | ||
return `[${timestamp}] ${level}: ${message}`; | ||
}) | ||
), | ||
}), | ||
new winston.transports.DailyRotateFile({ | ||
dirname: path.join(__dirname, '../../logs'), | ||
filename: 'application-%DATE%.log', | ||
datePattern: 'YYYY-MM-DD', | ||
zippedArchive: true, | ||
maxSize: '20m', | ||
maxFiles: '14d', | ||
}), | ||
], | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
p3
사용하지않는 IMPORT 제거부탁드립니다!