Skip to content

Conversation

@42inshin
Copy link
Member

@42inshin 42inshin commented Feb 23, 2025

해당 사항 (중복 선택)

  • FEAT : 새로운 기능 추가 및 개선
  • FIX : 기존 기능 수정 및 정상 동작을 위한 간단한 추가, 수정사항
  • BUG : 버그 수정
  • REFACTOR : 결과의 변경 없이 코드의 구조를 재조정
  • TEST : 테스트 코드 추가
  • DOCS : 코드가 아닌 문서를 수정한 경우
  • REMOVE : 파일을 삭제하는 작업만 수행
  • RENAME : 파일 또는 폴더명을 수정하거나 위치(경로)를 변경
  • ETC : 이외에 다른 경우 - 어떠한 사항인지 작성해주세요.

설명

🔗 관련 이슈 : closed #228

📝 작업 내용

Sentry는 애플리케이션의 오류 및 성능 문제를 모니터링하고 추적하는 데 사용되는 도구입니다.

0. 설치하기 전

Kong API Gateway에서 CORS Plugin에서 Sentry 로깅을 막습니다.
kong.yml의 CORS plugin 설정에서 Sentry 관련 헤더를 추가해야 합니다.

# Global CORS plugin
  - name: cors
    # ...
      headers:
        # 기존 headers...
        - sentry-trace
        - baggage
      exposed_headers:
        - sentry-trace
        - baggage

1. Sentry 설치

Sentry에 필요한 내용을 설치합니다.

pnpm add @sentry/react @sentry/tracing @sentry/vite-plugin

2. 환경변수 설정

Sentry DSN을 환경 변수 파일에 추가해야 합니다. .env 파일을 수정합니다.

VITE_IS_PROD=false
VITE_SENTRY_DSN=<sample-sentry-dsn>
SENTRY_AUTH_TOKEN=<sample-sentry-auth-token>

3. Sentry 초기화 및 설정

src/sentry.ts 파일을 생성하여 Sentry 설정을 추가합니다.

Sentry.init({
  dsn: import.meta.env.VITE_SENTRY_DSN,
  environment: import.meta.env.VITE_IS_PROD === 'true' ? 'production' : 'local',
  release: '^8.18.0',
  integrations: [
    Sentry.reactRouterV6BrowserTracingIntegration({
      useEffect,
      useLocation,
      useNavigationType,
      createRoutesFromChildren,
      matchRoutes,
    }),
    Sentry.replayIntegration(),
  ],
  tracesSampleRate: 1.0, //  Sentry가 수집할 성능 데이터의 비율
  tracePropagationTargets: ['localhost'], // Sentry가 추적할 URL
  replaysSessionSampleRate: 0.1, // 세션 재생의 샘플링 비율
  replaysOnErrorSampleRate: 1.0, // 오류가 발생한 세션의 재생 비율
});

4. Vite 설정

import { sentryVitePlugin } from '@sentry/vite-plugin';

export default defineConfig({
  plugins: [
   // .. 기존 플러그인들
    sentryVitePlugin({
      org: 'kickzo',
      project: 'kicktube',
      telemetry: false,
    }),
  ],
});

Sentry Vite 플러그인: 이 플러그인은 Vite 빌드 프로세스 중에 Sentry와 통합하여 소스 맵을 자동으로 업로드하고, 오류 추적을 위한 설정을 간소화합니다. 이를 통해 빌드된 애플리케이션에서 발생하는 오류를 Sentry에서 쉽게 추적할 수 있습니다.

5. 오류 추적 적용 예제

Sentry가 정상적으로 작동하는지 확인하기 위해 App.tsx 또는 특정 컴포넌트에서 오류 추적을 추가할 수 있습니다.

import * as Sentry from '@sentry/react';
import React from 'react';

function ErrorComponent() {
  const handleClick = () => {
    throw new Error('Sentry 테스트 오류');
  };

  return <button onClick={handleClick}>오류 발생</button>;
}

export default Sentry.withProfiler(ErrorComponent);

6. 실제 사용 예시

error, ErrorType, ErroMsg 를 받는 logAxiosError 함수를 만들어 로깅할 내용을 커스텀해서 Sentry로 보냅니다.

// 방 생성
createRoom: async (roomInfo: RoomRequestDto) => {
  try {
    const { data } = await instance.post<{ code: string }>('/rooms/create-room', roomInfo);
    return data;
  } catch (error) {
    logAxiosError(error, ErrorType.ROOM, '방 생성 실패');
    throw error;
  }
},

7. logAxiosError 함수

logAxiosError 함수는 Axios 요청 중 발생한 오류를 Sentry에 로깅하는 역할을 합니다.

HTTP 400 오류는 클라이언트 요청 오류로 간주하고 로깅하지 않습니다.

🏷️ tags (태그)

  • userId → 현재 로그인한 사용자 ID (없으면 anonymous)
  • api → 요청한 API의 URL
  • httpMethod → HTTP 메서드 (GET, POST, PUT 등)
  • httpStatusCode → HTTP 상태 코드 (ex. 500, 404)
import { captureException } from '@sentry/react';
import { AxiosError } from 'axios';
import { useUserStore } from '@/stores/useUserStore';

export const logAxiosError = (error: unknown, type: string, errorMsg: string) => {
  if (error instanceof AxiosError && error.response?.status === 400) return;

  if (error instanceof AxiosError) {
    error.message = errorMsg;
    captureException(error, {
      tags: {
        userId: useUserStore.getState().user?.userId ?? 'anonymous',
        api: error.response?.config.url,
        httpMethod: error.config?.method?.toUpperCase(),
        httpStatusCode: (error.response?.status ?? '').toString(),
      },
      level: 'error',
      extra: { type: type },
    });
  }
};

참고 문서

📸 스크린샷(optional)

Sentry Issues
image
Sentry Issues 상세내용
image
Sentry Issues 상세내용 - 에러 시 생성된 Session Replay
유저의 행동 패턴을 확인할 수 있습니다.
sentry
Discord로 받은 에러 알림 메시지
image

@42inshin 42inshin added FEAT 새로운 기능 추가 및 개선 🖥️FE 프론트엔드 작업 labels Feb 23, 2025
@42inshin 42inshin requested a review from juwon5272 February 23, 2025 04:49
@42inshin 42inshin self-assigned this Feb 23, 2025
Copy link
Collaborator

@juwon5272 juwon5272 left a comment

Choose a reason for hiding this comment

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

Sentry에 대해 자세히 적어주셔서 이해하기 편했습니다 감사합니다

@42inshin 42inshin merged commit d3349e7 into dev Feb 24, 2025
1 check passed
@42inshin 42inshin deleted the fe/dev/feat_sentry/#228 branch February 24, 2025 02:09
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

🖥️FE 프론트엔드 작업 FEAT 새로운 기능 추가 및 개선

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[FE] FEAT: Sentry 연동

3 participants