Skip to content

[한동우] sprint7 #194

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

Open
wants to merge 13 commits into
base: 한동우
Choose a base branch
from

Conversation

Dw-real
Copy link
Collaborator

@Dw-real Dw-real commented Jun 27, 2025

기본 요구사항

프로파일 기반 설정 관리

  • 개발, 운영 환경에 대한 프로파일을 구성하세요.
    • application-dev.yaml, application-prod.yaml 파일을 생성하세요.
    • 다음과 같은 설정값을 프로파일별로 분리하세요.
      • 데이터베이스 연결 정보
      • 서버 포트

로그 관리

  • Lombok의 @Slf4j 어노테이션을 활용해 로깅을 쉽게 추가할 수 있도록 구성하세요.

  • application.yaml에 기본 로깅 레벨을 설정하세요.

    • 기본적으로 info 레벨로 설정합니다.
  • 환경 별 적절한 로깅 레벨을 프로파일 별로 설정해보세요.

    • SQL 로그를 보기위해 설정했던 레벨은 유지합니다.
    • 우리가 작성한 프로젝트의 로그는 개발 환경에서 debug, 운영 환경에서는 info 레벨로 설정합니다.
  • Spring Boot의 기본 로깅 구현체인 Logback의 설정 파일을 구성하세요.

    • logback-spring.xml 파일을 생성하세요.

    • 다음 예시와 같은 로그 메시지를 출력하기 위한 로깅 패턴과 출력 방식을 커스터마이징하세요.

    • 로그 출력 예시

     # 패턴
    {년}-{월}-{일} {시}:{분}:{초}:{밀리초} [{스레드명}] {로그 레벨(5글자로 맞춤)} {로거 이름(최대 36글자)} - {로그 메시지}{줄바꿈}
    
     # 예시
    25-01-01 10:33:55.740 [main] DEBUG c.s.m.discodeit.DiscodeitApplication - Running with Spring Boot v3.4.0, Spring v6.2.0
    
  • 콘솔과 파일에 동시에 로그를 기록하도록 설정하세요.

    • 파일은 {프로젝트 루트}/.logs 경로에 저장되도록 설정하세요.
  • 로그 파일은 일자별로 롤링되도록 구성하세요.

  • 로그 파일은 30일간 보관하도록 구성하세요.

  • 서비스 레이어와 컨트롤러 레이어의 주요 메소드에 로깅을 추가하세요.

  • 로깅 레벨을 적절히 사용하세요: ERROR, WARN, INFO, DEBUG

  • 다음과 같은 메소드에 로깅을 추가하세요:

    • 사용자 생성/수정/삭제
    • 채널 생성/수정/삭제
    • 메시지 생성/수정/삭제
    • 파일 업로드/다운로드

예외 처리 고도화

  • 커스텀 예외를 설계하고 구현하세요.
    • 패키지명: com.sprint.mission.discodeit.exception[.{도메인}]
    • ErrorCode Enum 클래스를 통해 예외 코드명과 메시지를 정의하세요.
      • 아래는 예시입니다. 필요하다고 판단되는 다양한 코드를 정의하세요.
      • 예시
6ag3lzl9i-image
  • 모든 예외의 기본이 되는 DiscodeitException 클래스를 정의하세요.
    • 클래스 다이어그램
j5vtp941a-image
  - [x] details는 예외 발생 상황에 대한 추가정보를 저장하기 위한 속성입니다.
  - 예시
    - 조회 시도한 사용자의 ID 정보
    - 업데이트 시도한 PRIVATE 채널의 ID 정보

-[x] DiscodeitException을 상속하는 주요 도메인 별 메인 예외 클래스를 정의하세요.

  • UserException, ChannelException 등
  • 실제로 활용되는 클래스라기보다는 예외 클래스의 계층 구조를 명확하게 하기 위한 클래스 입니다.

-[x] 도메인 메인 예외 클래스를 상속하는 구체적인 예외 클래스를 정의하세요.

  • UserNotFoundException, UserAlreadyExistException 등 필요한 예외를 정의하세요.
  • 예시
a6f585icy-image

-[x] 기존에 구현했던 예외를 커스텀 예외로 대체하세요.
- NoSuchElementException
- IllegalArgumentException
- …

  • ErrorResponse를 통해 일관된 예외 응답을 정의하세요.
    • 클래스 다이어그램
3gqeampkw-image - `int status`: HTTP 상태코드 - `String exceptionType`: 발생한 예외의 클래스 이름
  • 앞서 정의한 ErrorResponse@RestControllerAdvice를 활용해 예외를 처리하는 예외 핸들러를 구현하세요.
    • 모든 핸들러는 일관된 응답(ErrorResponse)을 가져야 합니다.

유효성 검사

  • Spring Validation 의존성을 추가하세요.
  • 주요 Request DTO에 제약 조건 관련 어노테이션을 추구하세요.
    • @NotNull, @NotBlank, @Size, @Email
  • 컨트롤러에 @Valid 를 사용해 요청 데이터를 검증하세요.
  • 검증 실패 시 발생하는 MethodArgumentNotValidException을 전역 예외 핸들러에서 처리하세요.
  • 유효성 검증 실패 시 상세한 오류 메시지를 포함한 응답을 반환하세요.

Actuator

  • Spring Boot Actuator 의존성을 추가하세요.
  • 기본 Actuator 엔트포인트를 설정하세요.
    • health, info, metrics, loggers
  • Actuator info를 위한 애플리케이션 정보를 추가하세요.
    • 애플리케이션 이름: Discodeit
    • 애플리케이션 버전: 1.7.0
    • 자바 버전: 17
    • 스프링 부트 버전: 3.4.0
    • 주요 설정 정보
      • 데이터소스: url, 드라이버 클래스 이름
      • jpa: ddl-auto
      • storage 설정: type, path
      • multipart 설정: max-file-size, max-request-size
  • Spring Boot 서버를 실행 후 각종 정보를 확인해보세요.
    • /actuator/info
    • /actuator/metrics
    • /actuator/health
    • /actuator/loggers

단위 테스트

  • 서비스 레이어의 주요 메소드에 대한 단위 테스트를 작성하세요.
    • 다음 서비스의 핵심 메소드에 대해 각각 최소 2개 이상(성공, 실패)의 테스트 케이스를 작성하세요.
      • UserService: create, update, delete 메소드
      • ChannelService: create(PUBLIC, PRIVATE), update, delete, findByUserId 메소드
      • MessageService: create, update, delete, findByChannelId 메소드
    • Mockito를 활용해 Repository 의존성을 모의(mock)하세요.
    • BDDMockito를 활용해 테스트 가독성을 높이세요.

슬라이스 테스트

  • 레포지토리 레이어의 슬라이스 테스트를 작성하세요.
    • @DataJpaTest를 활용해 테스트를 구현하세요.
    • 테스트 환경을 구성하는 프로파일을 구성하세요.
      • application-test.yaml을 생성하세요.
      • 데이터소스는 H2 인메모리 데이터 베이스를 사용하고, PostgreSQL 호환 모드로 설정하세요.
      • H2 데이터베이스를 위해 필요한 의존성을 추가하세요.
      • 테스트 시작 시 스키마를 새로 생성하도록 설정하세요.
      • 디버깅에 용이하도록 로그 레벨을 적절히 설정하세요.
    • 테스트 실행 간 test 프로파일을 활성화 하세요.
    • JPA Audit 기능을 활성화 하기 위해 테스트 클래스에 @EnableJpaAuditing을 추가하세요.
    • 주요 레포지토리(User, Channel, Message)의 주요 쿼리 메소드에 대해 각각 최소 2개 이상(성공, 실패)의 테스트 케이스를 작성하세요.
      • 커스텀 쿼리 메소드

      • 페이징 및 정렬 메소드

      • 컨트롤러 레이어의 슬라이스 테스트를 작성하세요.

      • @WebMvcTest를 활용해 테스트를 구현하세요.

      • WebMvcTest에서 자동으로 등록되지 않는 유형의 Bean이 필요하다면 @import를 활용해 추가하세요.

        • 예시
@Import({ErrorCodeStatusMapper.class})
  - [x] 주요 컨트롤러(User, Channel, Message)에 대해 최소 2개 이상(성공, 실패)의 테스트 케이스를 작성하세요.
  - [x]  MockMvc를 활용해 컨트롤러를 테스트하세요.
  - [x]  서비스 레이어를 모의(mock)하여 컨트롤러 로직만 테스트하세요.
  - [x]  JSON 응답을 검증하는 테스트를 포함하세요.

통합 테스트

  • 통합 테스트 환경을 구성하세요.
    • @SpringBootTest를 활용해 Spring 애플리케이션 컨텍스트를 로드하세요.
    • H2 인메모리 데이터베이스를 활용하세요.
    • 테스트용 프로파일을 구성하세요.
  • 주요 API 엔드포인트에 대한 통합 테스트를 작성하세요.
    • 주요 API에 대해 최소 2개 이상의 테스트 케이스를 작성하세요.
      • 사용자 관련 API (생성, 수정, 삭제, 목록 조회)
      • 채널 관련 API (생성, 수정, 삭제)
      • 메시지 관련 API (생성, 수정, 삭제, 목록 조회)
      • 각 테스트는 @Transactional을 활용해 독립적으로 실행하세요.

심화 요구사항

MDC를 활용한 로깅 고도화

  • 요청 ID, 요청 URL, 요청 방식 등의 정보를 MDC에 추가하는 인터셉터를 구현하세요.
    • 클래스명: MDCLoggingInterceptor
    • 패키지명: com.**.discodeit.config
    • 요청 ID는 랜덤한 문자열로 생성합니다. (UUID)
    • 요청 ID는 응답 헤더에 포함시켜 더 많은 분석이 가능하도록 합니다.
      • 헤더 이름: Discodeit-Request-ID
  • WebMvcConfigurer를 통해 MDCLoggingInterceptor를 등록하세요.
    • 클래스명: WebMvcConfig
    • 패키지명: com.**.discodeit.config
  • Logback 패턴에 MDC 값을 포함시키세요.
    • 로그 출력 예시
   # 패턴
  {년}-{월}-{일} {시}:{분}:{초}:{밀리초} [{스레드명}] {로그 레벨(5글자로 맞춤)} {로거 이름(최대 36글자)} [{MDC:요청ID} | {MDC:요청 메소드} | {MDC:요청 URL}] - {로그 메시지}{줄바꿈}

   # 예시
  25-01-01 10:33:55.740 [main] DEBUG o.s.api.AbstractOpenApiResource [827cbc0b | GET | /v3/api-docs] - Init duration for springdoc-openapi is: 216 ms

Spring Boot Admin을 활용한 메트릭 가시화

  • Spring Boot Admin 서버를 구현할 모듈을 생성하세요.

  • admin 모듈의 메인 클래스에 @EnableAdminServer 어노테이션을 추가하고, 서버는 9091번 포트로 설정합니다.

import de.codecentric.boot.admin.server.config.EnableAdminServer;

@SpringBootApplication
@EnableAdminServer
public class AdminApplication {
    public static void main(String[] args) {
        SpringApplication.run(AdminApplication.class, args);
    }
}
# application.yaml
spring:
    application:
        name: admin
server:
    port: 9091
  • admin 서버 실행 후 localhost:9090/applications 에 접속해봅니다.

  • discodeit 프로젝트에 Spring Boot Admin Client를 적용합니다.
    -[x] 의존성 추가

dependencies {
    ...
    implementation 'de.codecentric:spring-boot-admin-starter-client:3.4.5
}
  • admin 서버에 등록될 수 있도록 설정 정보를 추가합니다.
# application.yml
spring:
  application:
    name: discodeit
    ...
  boot:
    admin:
      client:
        instance:
          name: discodeit
...
# application-dev.yml
spring:
  application:
    name: discodeit
    ...
  boot:
    admin:
      client:
        url: http://localhost:9090
...
# application-prod.yml
spring:
  application:
    name: discodeit
    ...
  boot:
    admin:
      client:
        url: ${SPRING_BOOT_ADMIN_CLIENT_URL}
...
  • discodeit 서버를 실행하고, admin 대시보드에 discodeit 인스턴스가 추가되었는지 확인합니다.

테스트 커버리지 관리

  • JaCoCo 플러그인을 추가하세요
plugins {
    id 'jacoco'
}

test {
    finalizedBy jacocoTestReport
}

jacocoTestReport {
    dependsOn test
    reports {
        xml.required = true
        html.required = true
    }
}
  • 테스트 실행 후 생성된 리포트를 분석해보세요.
    • 리포트는 build/reports/jacoco 경로에서 확인할 수 있습니다.
  • com.sprint.mission.discodeit.service.basic 패키지에 대해서 60% 이상의 코드 커버리지를 달성하세요.

스크린샷

스크린샷 2025-06-27 오후 11 11 53 스크린샷 2025-06-27 오후 11 09 56

멘토에게

  • 셀프 코드 리뷰를 통해 질문 이어가겠습니다.

@Dw-real Dw-real requested a review from ssjf409 June 30, 2025 01:03
@Dw-real Dw-real added the 매운맛🔥 뒤는 없습니다. 그냥 필터 없이 말해주세요. 책임은 제가 집니다. label Jun 30, 2025
boot:
admin:
client:
url: http://localhost:9091
Copy link
Collaborator

Choose a reason for hiding this comment

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

요구사항에서는 포트번호를 9090으로 하라고 되어있는데 9091로 하신 이유가 있을까요?

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

이전에 스프링부트 애플리케이션 모니터링을 위해서 프로메테우스와 그라파나를 사용한 적이 있는데 프로메테우스의 기본 포트가 9090 포트라서 충돌이 발생해서 9091로 설정했습니다.

dialect: org.hibernate.dialect.PostgreSQLDialect

server:
port: 8080
Copy link
Collaborator

Choose a reason for hiding this comment

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

application-prod.yaml에 없는 설정은 application.yaml에서 가져오기 때문에 profile을 prod로 실행해도 일부 설정은 들어올거에요.
특히, 로깅관련해서 Debug레벨까지 로깅하는거랑 데이터 바인드까지 하는건 성능상이나 보안상 문제가 될 수 있어보여요.

https://github.com/codeit-bootcamp-spring/3-sprint-mission/pull/194/files

application.yaml을 없애시거나 아니면 최소화해주세요.
그리고 prod의 설정은 최대한 보수적으로 설정해주세요.

그렇게 하는게 application-prod.yaml만 봐도 이행할 수 있어서 명식적이고 실수할 여지가 적어보여요.

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

확인하고 수정해보도록 하겠습니다!

</encoder>
</appender>

<!-- 비즈니스 파일 로그 (business.log) -->
Copy link
Collaborator

Choose a reason for hiding this comment

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

비즈니스 파일 로그는 어떤 경우에 남기는건가요? 잘 이해가 안되서 여쭤봅니다.

구분하신 의도도 설명해주시면 감사드립니다.

Copy link
Collaborator Author

@Dw-real Dw-real Jul 7, 2025

Choose a reason for hiding this comment

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

UserService, MessageService, ChannelService에 있는 주요 비즈니스 로직을 로깅하기 위해 분리했습니다!

image

Comment on lines +24 to +34
<appender name="APP_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${LOG_PATH}/${LOG_FILE_NAME}-application.log</file>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>${LOG_PATH}/${LOG_FILE_NAME}-application-%d{yyyy-MM-dd}.log</fileNamePattern>
<maxHistory>30</maxHistory>
</rollingPolicy>
<encoder>
<pattern>${FILE_LOG_PATTERN}</pattern>
<charset>UTF-8</charset>
</encoder>
</appender>
Copy link
Collaborator

Choose a reason for hiding this comment

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

로깅 파일을 시간단위로 롤링하는 정책은 현업에서도 많이 쓰고 굉장히 잘 하신것 같아요.
하지만 파일이 너무 커져서 문제가 되는 경우도 있거든요.
그래서 보통은 최대 파일크기도 같이 설정으로 걸어둬요.

아래 파일 크기 + 시간 주기로 롤링하는 정책입니다.

<appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
  <file>./logs/app.log</file>
  <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
    <fileNamePattern>./logs/app.%d{yyyy-MM-dd}.%i.log</fileNamePattern>
    <maxFileSize>100MB</maxFileSize> <!-- 파일 하나가 100MB 넘으면 새로 만듦 -->
    <maxHistory>30</maxHistory>       <!-- 최대 30일 보관 -->
    <totalSizeCap>5GB</totalSizeCap>  <!-- 전체 합이 5GB 넘으면 오래된 것부터 삭제 -->
  </rollingPolicy>
  <encoder>
    <pattern>${ROLLING_PATTERN}</pattern>
  </encoder>
</appender>

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

로깅이 쌓여서 로깅 파일 사이즈가 커진다는 생각을 미처 생각하지 못했었네요. 참고하겠습니다!


@Test
@DisplayName("Private 채널 등록 프로세스가 모든 계층에서 올바르게 동작해야 한다.")
void completeCreatePrivateChannelIntegration() {
Copy link
Collaborator

Choose a reason for hiding this comment

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

when 절은 최대한 짧게 작성하는게 좋습니다. 가급적 1줄로 작성하는게 제일 좋습니다. 과학 실험을 할때도 최대한 환경을 통제해놓고 한가지의 변경만 가하면서 변화들을 확인하잖아요. 마찬가지 이유로 then 부분은 최대한 심플하게 하는게 좋습니다.

given-when-then을 좀 더 명확하게 구분하기 위해서 각 절 내부에서는 빈 공백 줄바꿈은 최소화하고 절이 넘어갈때만 사용하는게 좋습니다.

@Test
@DisplayName("Private 채널 등록 시 채널, 참여자, ReadStatus가 올바르게 생성된다.")
void createPrivateChannel_shouldPersistAllRelatedData() {
    // given
    PrivateChannelDto request = new PrivateChannelDto(List.of(userId1, userId2));

    // when
    ChannelResponseDto result = channelService.createPrivateChannel(request);

    // then
    assertNotNull(result);
    assertEquals(ChannelType.PRIVATE, result.type());
    assertEquals(userId1, result.participants().get(0).id());
    assertNull(result.lastMessageAt(), "초기에는 메시지가 없어야 하므로 lastMessageAt은 null이어야 합니다.");
    Optional<Channel> foundChannel = channelRepository.findById(result.id());
    assertTrue(foundChannel.isPresent(), "채널이 저장되어 있어야 합니다.");
    List<ReadStatus> readStatuses = readStatusRepository.findAllByUserId(userId1);
    assertEquals(1, readStatuses.size(), "유저 1명의 ReadStatus가 정확히 하나 생성되어야 합니다.");
}

Comment on lines +59 to +65
mockMvc.perform(post("/api/channels/public")
.contentType(MediaType.APPLICATION_JSON_VALUE)
.content(objectMapper.writeValueAsString(request)))
.andExpect(status().isCreated())
.andExpect(jsonPath("$.id").value(channelId.toString()))
.andExpect(jsonPath("$.name").value("public"))
.andExpect(jsonPath("$.description").value("test channel"));
Copy link
Collaborator

Choose a reason for hiding this comment

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

여기는 When과 then이 섞여있는걸로 보여요. 분리해주세요.

Comment on lines +36 to +37
Channel savedChannel = channelRepository.save(channel);
Optional<Channel> foundChannel = channelRepository.findById(savedChannel.getId());
Copy link
Collaborator

Choose a reason for hiding this comment

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

저장을 테스트 하고 싶으신건지, 조회를 테스트하고 싶은건지 명확하게 할 필요가 있다 생각합니다.
저장을 테스트하고 싶은거면 when에는 Channel savedChannel = channelRepository.save(channel); 남겨두시고
조회를 테스트하고 싶으신거면 Channel savedChannel = channelRepository.save(channel);을 given으로 옮겨주세요.

when 절에 이렇게 두가지 이상의 행동을 하는건 테스트의 변수를 너무 많이 만들어 이해하기 어렵고 테스트를 복잡하게 만듭니다.

given(userRepository.findById(notExistId)).willReturn(Optional.empty());

// when
assertThrows(NotFoundUserException.class, () -> userService.findById(notExistId));
Copy link
Collaborator

Choose a reason for hiding this comment

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

이것도 when이 아니라 when, then이라 생가됩니다. 아래처럼 고쳐주세요.

@Test
@DisplayName("등록되지 않은 ID로 사용자를 조회하면 NotFoundUserException이 발생해야 한다.")
void givenNonexistentUserId_whenFindById_thenThrowNotFoundUserException() {
    // given
    UUID notExistId = UUID.randomUUID();
    given(userRepository.findById(notExistId)).willReturn(Optional.empty());

    // when
    Throwable thrown = catchThrowable(() -> userService.findById(notExistId));

    // then
    assertThat(thrown)
        .isInstanceOf(NotFoundUserException.class)
        .hasMessageContaining("사용자");
    verify(userRepository).findById(notExistId);
    verifyNoInteractions(userStatusRepository, userMapper); // 사용자 없으면 이후 로직 없어야 함
}

@ssjf409
Copy link
Collaborator

ssjf409 commented Jul 2, 2025

전체적으로 잘 작성해주셨습니다. 테스트 코드에서 when절에 then이 섞여 있는 코드가 일부 있습니다. 제가 일일이 다 코멘트 달지 않았습니다. 작성하셨던 코드 다시 확인 해보시면서 when절에 then이 섞여 있는거 아닌지 고민해봐주시면 감사드립니다.

yaml 파일도 application.yaml의 설정이 profile을 "prod"로 설정해도 포함될 수 있다는 걸 주의하셔야 할 것 같아요.
장애로 발생하기 쉬운 케이스라 생각되고 최대한 명시적으로 표현하는게 중요합니다. 특히 협업을 하려면 다른 사람이 내가 작성했던 코드를 전체를 다 고려하는게 아니라 일부분만 보고 판단할 수 있기 때문에 잘못 이해할 수 있는 경우들을 최대한 줄이는게 중요합니다.

@Dw-real
Copy link
Collaborator Author

Dw-real commented Jul 7, 2025

피드백 감사합니다! 테스트 코드 작성 부분은 아직 익숙하지 않아서 when then이 섞여 있는 부분도 많고 목적이 애매한 테스트 코드를 많이 작성한 것 같습니다. 리뷰 주신 부분은 미션8 pr에 커밋해서 올리겠습니다

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
매운맛🔥 뒤는 없습니다. 그냥 필터 없이 말해주세요. 책임은 제가 집니다.
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants