Skip to content

[25.07.12 / TASK-92] Refactor - API에 Sentry 추가 #40

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

Merged
merged 4 commits into from
Jul 13, 2025

Conversation

six-standard
Copy link
Member

@six-standard six-standard commented Jul 12, 2025

🔥 변경 사항

API와 센트리를 연결하였습니다.
사실 연결 자체는 목요일쯤 끝냈는데, 이전에 현우님이 말씀해주신 '복잡한 방식'을 계속 시도하다 보니 밀렸네요..
결론적으로, 복잡한 방식은 제외하고 단순한 방식만 반영해서 올렸습니다.

🏷 관련 이슈

  • 관련 이슈: X

📸 스크린샷 (UI 변경 시 필수)

스크린샷 2025-07-12 오후 6 53 27

📌 체크리스트

  • 기능이 정상적으로 동작하는지 테스트 완료
  • 코드 스타일 가이드 준수 여부 확인
  • 관련 문서 업데이트 완료 (필요 시)

Summary by CodeRabbit

  • 신규 기능

    • Sentry를 통한 에러 및 성능 모니터링 기능이 추가되었습니다.
    • 에러 발생 시 Sentry로 예외가 자동 전송됩니다.
  • 환경설정

    • 환경 변수 예시에 Sentry DSN 및 클라이언트 시크릿 항목이 추가되었습니다.
  • 의존성 추가

    • Sentry Node.js SDK가 새롭게 추가되었습니다.

@six-standard six-standard self-assigned this Jul 12, 2025
@six-standard six-standard added the enhancement New feature or request label Jul 12, 2025
Copy link

Copy link
Contributor

coderabbitai bot commented Jul 12, 2025

"""

Walkthrough

Sentry 오류 및 성능 모니터링 도구가 프로젝트에 통합되었습니다. 환경 변수, 패키지 의존성, Sentry 초기화 설정, 그리고 오류 처리 미들웨어가 Sentry로 오류를 전송하도록 수정되었습니다. 새로운 설정 파일이 추가되고, 기존 애플리케이션 초기화 흐름이 업데이트되었습니다.

Changes

파일/경로 변경 요약
.env.sample Sentry 관련 환경변수(SENTRY_CLIENT_SECRET, SENTRY_DSN) 추가 및 주석 수정
package.json @sentry/node 패키지 의존성 추가
src/configs/sentry.config.ts Sentry 초기화 함수(initSentry) 및 설정 파일 신규 추가
src/app.ts Sentry 초기화 함수 호출 추가 및 포맷팅 소폭 수정
src/middlewares/errorHandling.middleware.ts 오류 발생 시 Sentry로 예외 전송 로직 추가
.github/workflows/test-ci.yaml CI 환경 .env 파일에 SENTRY_DSN 환경변수 추가

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant App
    participant Sentry

    User->>App: 요청
    App->>App: 환경변수 로드
    App->>App: initSentry() 호출
    App->>Sentry: Sentry 초기화
    User->>App: 오류 발생 요청
    App->>App: errorHandlingMiddleware 실행
    App->>Sentry: Sentry.captureException(err) (비정상 오류 시)
    App->>User: 500 Internal Server Error 응답
Loading

Suggested reviewers

  • ooheunda
  • Jihyun3478

Poem

🐰
센트리와 함께 토끼가 뛴다,
오류가 오면 슬쩍 보고한다.
환경변수도 새로 추가,
패키지 설치도 빠짐없다.
이제 우리 서비스,
버그도 놓치지 않는다!
🎉
"""

✨ Finishing Touches
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feature/api-sentry-connection

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai auto-generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between b0df207 and 9c70935.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (5)
  • .env.sample (1 hunks)
  • package.json (1 hunks)
  • src/app.ts (2 hunks)
  • src/configs/sentry.config.ts (1 hunks)
  • src/middlewares/errorHandling.middleware.ts (2 hunks)
🧰 Additional context used
🧠 Learnings (2)
src/app.ts (6)
Learnt from: HA0N1
PR: Check-Data-Out/velog-dashboard-v2-api#5
File: src/middlewares/error-handling.middleware.ts:1-2
Timestamp: 2024-12-04T14:05:58.537Z
Learning: `src/middlewares/error-handling.middleware.ts` 파일의 에러 핸들링 미들웨어에서 `NextFunction`을 사용하지 않으며, `err`은 커스텀 에러로 사용되므로 `NextFunction`과 `ErrorRequestHandler`를 임포트할 필요가 없습니다.
Learnt from: HA0N1
PR: Check-Data-Out/velog-dashboard-v2-api#4
File: src/middlewares/auth.middleware.ts:48-49
Timestamp: 2024-11-29T14:21:32.376Z
Learning: `auth.middleware.ts` 파일에서 `VELOG_API_URL`은 개발 및 배포 환경 모두에서 고정된 값으로, 환경 변수로 이동하지 않고 상수로 설정하여 가독성을 높이는 것이 좋습니다.
Learnt from: HA0N1
PR: Check-Data-Out/velog-dashboard-v2-api#5
File: src/middlewares/auth.middleware.ts:116-117
Timestamp: 2024-12-04T13:26:58.075Z
Learning: 'velog-dashboard-v2-api' 코드베이스에서는 `src/types/express.d.ts` 파일에서 Express의 `Request` 인터페이스를 확장하여 `user`와 `tokens` 속성을 추가하였습니다.
Learnt from: HA0N1
PR: Check-Data-Out/velog-dashboard-v2-api#5
File: src/middlewares/error-handling.middleware.ts:4-7
Timestamp: 2024-12-04T13:59:57.198Z
Learning: 프로젝트에서 `Express` 네임스페이스에 `CustomError` 타입이 정의되어 있습니다.
Learnt from: HA0N1
PR: Check-Data-Out/velog-dashboard-v2-api#5
File: src/types/dto/user-with-token.dto.ts:3-26
Timestamp: 2024-12-04T13:28:34.692Z
Learning: In `src/types/dto/user-with-token.dto.ts`, since the project is using Express instead of NestJS, `nestjs/swagger` cannot be used. Documentation will be implemented later using an Express-specific Swagger library.
Learnt from: HA0N1
PR: Check-Data-Out/velog-dashboard-v2-api#6
File: src/controllers/user.controller.ts:11-12
Timestamp: 2024-12-06T14:29:50.385Z
Learning: TypeScript Express 프로젝트에서, `Express.Request` 인터페이스는 전역으로 확장되어 `user`와 `tokens` 프로퍼티를 포함합니다. `user` 프로퍼티는 `VelogUserLoginResponse | VelogUserVerifyResponse` 타입이고, `tokens`는 `accessToken`과 `refreshToken`을 가진 객체입니다.
src/middlewares/errorHandling.middleware.ts (2)
Learnt from: HA0N1
PR: Check-Data-Out/velog-dashboard-v2-api#5
File: src/middlewares/error-handling.middleware.ts:1-2
Timestamp: 2024-12-04T14:05:58.537Z
Learning: `src/middlewares/error-handling.middleware.ts` 파일의 에러 핸들링 미들웨어에서 `NextFunction`을 사용하지 않으며, `err`은 커스텀 에러로 사용되므로 `NextFunction`과 `ErrorRequestHandler`를 임포트할 필요가 없습니다.
Learnt from: HA0N1
PR: Check-Data-Out/velog-dashboard-v2-api#5
File: src/middlewares/error-handling.middleware.ts:4-7
Timestamp: 2024-12-04T13:59:57.198Z
Learning: 프로젝트에서 `Express` 네임스페이스에 `CustomError` 타입이 정의되어 있습니다.
🧬 Code Graph Analysis (1)
src/app.ts (1)
src/configs/sentry.config.ts (1)
  • initSentry (6-24)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (4)
  • GitHub Check: build-and-test (23)
  • GitHub Check: build-and-test (21)
  • GitHub Check: build-and-test (20)
  • GitHub Check: build-and-test (22)
🔇 Additional comments (6)
package.json (1)

27-27: Sentry 의존성 추가 승인

공식 Sentry Node.js SDK의 최신 버전을 추가한 것이 적절합니다.

src/configs/sentry.config.ts (1)

12-22: Sentry 설정이 적절히 구성됨

트레이스 샘플링 비율(10%), 디버그 모드 비활성화, HTTP/Express 통합 설정이 프로덕션 환경에 적합하게 구성되었습니다.

src/app.ts (2)

12-12: Sentry 초기화 import 승인

Sentry 설정 모듈을 적절히 임포트했습니다.


16-17: Sentry 초기화 시점이 적절함

환경 변수 로드 후 즉시 Sentry를 초기화하는 것이 모범 사례입니다. 애플리케이션 전체에서 에러 추적이 가능하도록 올바르게 설정되었습니다.

src/middlewares/errorHandling.middleware.ts (2)

4-4: Sentry import 승인

에러 핸들링 미들웨어에 Sentry를 적절히 임포트했습니다.


19-22: Sentry 에러 캡처 로직이 올바르게 구현됨

커스텀 에러가 아닌 경우에만 Sentry로 에러를 전송하는 것이 적절합니다. 예상치 못한 시스템 에러만 Sentry로 추적하고, 비즈니스 로직 에러는 기존 방식으로 처리하는 것이 모범 사례입니다.

Copy link
Member

@Nuung Nuung left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

총평 이전에 hotfix 가 필수인 부분들이 있어서,, 해당 부분 바꿔주세요 ㅠㅠ
그리고 batch (CI/CD) flow 에 영향을 주지 않도록, default 값에 대한 명시가 필요할 것 같아요.

더욱이 Notion 에 업데이트 되었나요?

.env.sample Outdated
@@ -24,3 +24,4 @@ POSTGRES_PORT=5432
# ETC
SLACK_WEBHOOK_URL=https://hooks.slack.com/services
SLACK_CLIENT_SECRET=374708bedd34ae70f814471ff24db7dedc4b9bee06a7e8ef9255a4f6c8bd9049 # 실제 키를 사용하세요
SLACK_DSN=https://ingest.us.sentry.io
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

환경변수... 주의 부탁 드립니다.. 네이밍... 이번에도..ㅠㅠ

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

이 부분을 제가 계속 놓치고 있었던 것 같네요;;
슬랙 쪽에서 발급받는 부분은 SLACK, 센트리 쪽에서 발급받는 부분은 SENTRY로 통일하는게 좋을 것 같습니다!
물론 두 값 사이에 줄바꿈은 넣어야 할 것 같네요

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@six-standard 그 도메인을 나누는 데에는 전혀 이견 없습니다.
근데 제가 말드리고 있는 포인트는 지금 PR에서 기준님은 전혀 지금 SLACK 이랑 관련된 값을 건들이지 않았어요. 지금은 철저하게 SENTRY 관련된 값입니다.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

이해했습니다.
말씀해주신대로 수정해서 반영했습니다!


export const initSentry = () => {
Sentry.init({
dsn: process.env.SENTRY_DSN,
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

SENTRY_DSN vs SLACK_DSN ...

Copy link
Member Author

@six-standard six-standard Jul 12, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

이 부분을 제가 계속 놓치고 있었던 것 같네요;;
슬랙 쪽에서 발급받는 부분은 SLACK, 센트리 쪽에서 발급받는 부분은 SENTRY로 통일하는게 좋을 것 같습니다!
물론 두 값 사이에 줄바꿈은 넣어야 할 것 같네요

@Nuung 이전에도 제가 놓친 부분이 또 있었던 것으로 아는데, 이런 식으로 맞추는건 어떠신가요?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

아뇨 이게 slack 이면 절대 안될 것 같아요.
슬랙 쪽에서 발급받는 부분은 SLACK 인데 지금 PR 은 slack 쪽에서 발급 받는게 하나도 없어요. dsn 값은 무조건 SENTRY 가 맞습니다. @six-standard

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

이 부분도 방금 말씀해주신대로 맞췄습니다.

export const initSentry = () => {
Sentry.init({
dsn: process.env.SENTRY_DSN,
release: 'production',
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

코드레빗의 코멘트가 매우 중요한데요..! 그냥 production 이면 저희가 local 이랑 구분을 못해요

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

테스트 목적으로 수정하다가 놓친 듯 합니다;;
수정해두었습니다!

@@ -15,7 +16,10 @@ export const errorHandlingMiddleware: ErrorRequestHandler = (
.json({ success: false, message: err.message, error: { code: err.code, statusCode: err.statusCode } });
return;
}

Sentry.captureException(err);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

만약 여기서 에러가 발생한다면?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sentry에서 전역 오류로 감지해서 다시 전송하는 것으로 알고 있습니다!

@six-standard six-standard requested a review from Nuung July 12, 2025 17:34
@six-standard
Copy link
Member Author

six-standard commented Jul 12, 2025

총평 이전에 hotfix 가 필수인 부분들이 있어서,, 해당 부분 바꿔주세요 ㅠㅠ 그리고 batch (CI/CD) flow 에 영향을 주지 않도록, default 값에 대한 명시가 필요할 것 같아요.

더욱이 Notion 에 업데이트 되었나요?

네이밍 쪽에 좀 문제가 많은 것 같아 이번에 확실히 하고 가야 할 것 같네요;;

느낌상 제 무의식이 제가 네이밍쪽 리뷰에서 말씀드린 것처럼 "슬랙" 도메인과 "센트리" 도메인을 분리해서 적용하고 있는 것 같습니다!
이전에 프론트엔드 쪽에서도 네이밍으로 지적이 한 번 들어왔었던 것으로 기억하는데, 머리에서 자동으로 두 도메인을 분리하다 보니 네이밍에 문제가 없다고 판단되어서 넘기느라 제대로 처리가 안 되었었던 것 같네요..

사실 좋은 방향인지는 애매하나 저는 이 부분을 계속 분리하는 쪽으로 유지하는게 덜 헷갈릴 것 같다고 생각하는데, 현우님 생각은 어떠신지 궁금합니다!

제가 포인트를 못 잡고 있었네요;;
말씀해주신대로 전부 수정해두었습니다!
아 그리고 노션은 이미 업데이트해두었습니다.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between bf33d9d and 39c91f4.

📒 Files selected for processing (2)
  • .env.sample (1 hunks)
  • .github/workflows/test-ci.yaml (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • .github/workflows/test-ci.yaml
🧰 Additional context used
🧠 Learnings (1)
.env.sample (3)
Learnt from: HA0N1
PR: Check-Data-Out/velog-dashboard-v2-api#4
File: .env.sample:7-16
Timestamp: 2024-11-29T14:01:55.277Z
Learning: The AES keys provided in the `.env.sample` file are sample values and not actual encryption keys.
Learnt from: HA0N1
PR: Check-Data-Out/velog-dashboard-v2-api#4
File: .env.sample:2-6
Timestamp: 2024-11-29T14:01:26.914Z
Learning: `velog-dashboard-v2-api` 프로젝트의 `.env.sample` 파일에서는 데이터베이스 접속 정보를 포함한 환경 변수에 예시 값을 사용하며, 이는 실제 자격 증명이 아니므로 그대로 두어도 됩니다.
Learnt from: HA0N1
PR: Check-Data-Out/velog-dashboard-v2-api#4
File: src/middlewares/auth.middleware.ts:48-49
Timestamp: 2024-11-29T14:21:32.376Z
Learning: `auth.middleware.ts` 파일에서 `VELOG_API_URL`은 개발 및 배포 환경 모두에서 고정된 값으로, 환경 변수로 이동하지 않고 상수로 설정하여 가독성을 높이는 것이 좋습니다.
🪛 Gitleaks (8.26.0)
.env.sample

28-28: Found a Sentry.io Access Token (old format), risking unauthorized access to error tracking services and sensitive application data.

(sentry-access-token)

⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (4)
  • GitHub Check: build-and-test (22)
  • GitHub Check: build-and-test (23)
  • GitHub Check: build-and-test (21)
  • GitHub Check: build-and-test (20)
🔇 Additional comments (1)
.env.sample (1)

24-29: 환경 변수 참조 일치 확인 완료

레포 전체에서 SENTRY_DSN / SENTRY_CLIENT_SECRET만 사용 중이며, SLACK_DSN과 같은 오타·잔존 레퍼런스는 존재하지 않습니다. 추가 확인이나 수정은 필요 없어 보입니다.

SLACK_CLIENT_SECRET=374708bedd34ae70f814471ff24db7dedc4b9bee06a7e8ef9255a4f6c8bd9049 # 실제 키를 사용하세요

# Sentry Hook
SENTRY_CLIENT_SECRET=374708bedd34ae70f814471ff24db7dedc4b9bee06a7e8ef9255a4f6c8bd9049 # 실제 키를 사용하세요
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

이거 제가 배포 핫픽스 하면서 SENTRY_CLIENT_SECRET 로 바궛다고 생각했는데 아니엇나!! 이 부분을 말하신거군요!

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

저도 이 부분이 이상하다 싶어서 이번에 다 수정해두었는데, 지난번에 놓치신 부분이었나 봅니다.
사실 이런 식으로 분리하는게 필요하다 생각은 했었는데, 막상 실행을 못 했었네요;;

@@ -59,6 +59,7 @@ jobs:
echo "POSTGRES_PASSWORD=${{ secrets.POSTGRES_PASSWORD }}" >> .env
echo "POSTGRES_PORT=${{ secrets.POSTGRES_PORT }}" >> .env
echo "SENTRY_CLIENT_SECRET=${{ secrets.SENTRY_CLIENT_SECRET }}" >> .env
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

이거봐! 내가 분명 바꿧는데! ㅋㅋㅋㅋ과거 코드도 ㅋㅋㅋ 실제 환경은 다 SENTRY_CLIENT_SECRET 쓰긴할거에유

@six-standard six-standard requested a review from Nuung July 12, 2025 17:52
@six-standard six-standard merged commit 42f4be5 into main Jul 13, 2025
5 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants