Spring Boot :: Senty 도입

JaeHwan·2023년 8월 18일
0

Spring Boot

목록 보기
2/8
post-thumbnail

Sentry 테스트 도입

🗒️ Sentry 란

간단하고 공신력 있는 GPT 의 발언을 인용하겠습니다.
요약하자면

에러 및 로그를 추적하여 모니터링하기 편하고 쉽게 만들어주어 sentry를 통해 개발들이 빠르게 문제를 해결하고 안정성을 높일 수 있게 도와주는 도구 입니다.

🌿 Spring Boot로 써보자!

🛠️ 환경설정

우선 gradle을 이용해 sentry 라이브러리를 가져옵니다.

implementation 'io.sentry:sentry-spring-boot-starter:6.28.0'
implementation 'io.sentry:sentry-logback:6.27.0'
( logback의 경우 sentryspan을 사용해 수집되는 로그 및 에러를 커스텀 이름으로 보여질 수 있게
  도와줍니다.)

라이브러리를 가져온 뒤 Sentry에 회원가입 및 로그인하고 만든 프로젝트에서 dsn 경로를 가져와 Spring yaml 파일에 설정해 줍니다.

application.yml ( 공통 yaml 파일에 넣어줍니다.)

sentry:
  dsn: "sentry dsn"
  traces-sample-rate: 1.0
  send-default-pii: true ( 해당 설정을 이용해서 유저를 추적 및 기록할 수 있다.)

send-default-pii: true 예)

application-local (dev, prod … )
구분되는 yaml 파일에는 sentry에서 수집할 운영환경을 구분해줍니다.

sentry:
  environment: local ( dev, prod...)

👨🏻‍💻 코드추가


@Slf4j
@RestControllerAdvice
@RequiredArgsConstructor
public class CustomExceptionHandler {
    private final FilterErrorUtils filterErrorUtils;

    @ExceptionHandler(RestException.class)
    public ResponseEntity<CommonResponseDto> restExceptionHandler(RestException e) {
        e.printStackTrace();
        CommonResponseDto responseDto = CommonResponseDto.builder()
                .success(false)
                .status(e.getHttpStatus().value())
                .message(e.getMessage())
                .data(new ArrayList<>())
                .build();
        return new ResponseEntity<>(responseDto, e.getHttpStatus());
    }

    @ExceptionHandler(BadCredentialsException.class)
    public ResponseEntity<CommonResponseDto> badCredentialExceptionHandler(BadCredentialsException e) {
        Sentry.captureException(e);
        CommonResponseDto responseDto = CommonResponseDto.builder()
                .success(false)
                .status(HttpStatus.UNAUTHORIZED.value())
                .message(e.getMessage())
                .data(new ArrayList<>())
                .build();
        return new ResponseEntity<>(responseDto, HttpStatus.UNAUTHORIZED);
    }
		{
		... 중략
		}
}

@RestControllerAdvice 의 AOP 기능을 이용해서 controller의 실행 전후로 실행되는 ExceptionHandler가 있습니다. AOP 기능을 이용해서 에러 발생마다 Sentry 코드를 적용하지 않아도 쉽게 수집할 수 있게 작성했습니다.
RestException의 경우 개발자가 만든 커스텀에러기 때문에 sentry에서 수집하여 issue로 넘어가지 않게 설정을 해주었고, 다른 에러의 경우

Sentry.captureException( error 객체 )

를 이용해 sentry에서 에러를 수집 후 issue 문단에 넘기도록 설정해주었습니다. 이렇게 설정할 경우

🖼️ 예시)

위와 같이 issue 탭을 이용해 확인할 수 있으며 Jira처럼 담당자 설정까지 가능한 것으로 확인됩니다.

✏️ 할 일

slack 등 현재 연구소에서 사용하고 있는 협업툴과의 연동 테스트가 필요해보입니다.

profile
Flutter를 사랑하는 근데 이제 백엔드를 곁들인

2개의 댓글

comment-user-thumbnail
2023년 8월 18일

개발자로서 배울 점이 많은 글이었습니다. 감사합니다.

1개의 답글