Skip to content
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

refactor: 로깅 구체화 하기 #318

Merged
merged 42 commits into from
Oct 4, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
42 commits
Select commit Hold shift + click to select a range
c30b16a
feat: 로그 필터 구현
chaewon121 Sep 7, 2023
6da3a22
fix: application prod를 local로 수정
chaewon121 Sep 7, 2023
65e6acf
feat: logback gradle 의존성 추가
chaewon121 Sep 7, 2023
29ad30b
feat: 기존 로깅 파일 삭제
chaewon121 Sep 7, 2023
5bb228d
feat: logback xml 파일 설정
chaewon121 Sep 7, 2023
16261d0
feat: 로그 필터 구현
chaewon121 Sep 7, 2023
c41e169
feat: mdc 필터 구현
chaewon121 Sep 7, 2023
a14a39d
feat: 필터 빈등록
chaewon121 Sep 7, 2023
cea0006
feat: exceptionHandler 수정
chaewon121 Sep 7, 2023
24852e1
feat: 깃허브 설정
chaewon121 Sep 13, 2023
7b0a2c6
refactor: mdc 이넘 추가
chaewon121 Sep 13, 2023
17c3b6c
refactor: info 로그 출력 message추가
chaewon121 Sep 13, 2023
0be774e
refactor: 추가 메서드 삭제
chaewon121 Sep 13, 2023
43ca214
refactor: 사용하지 않는 상수 삭제
chaewon121 Sep 13, 2023
b582c99
chore: 쿼리 튜닝 및 성능 조회를 위한 변경사항
dooboocookie Sep 21, 2023
ac65e19
chore: 쿼리 정보 로그 삭제
dooboocookie Sep 21, 2023
71b71d2
feat: 로깅 추가 (#359)
dooboocookie Sep 21, 2023
70b3646
fix: 워크플로우 수정
dooboocookie Sep 21, 2023
0628f07
hotfix: PlayerRepository.findAll() 호출 시 N+1 문제 수정 (#360)
dooboocookie Sep 21, 2023
1939190
refactor: 코드컨벤션 젹용
chaewon121 Sep 26, 2023
5304cdd
refactor: 날짜 수정
chaewon121 Sep 26, 2023
3dbe5a2
refactor: mdc 필터 제거
chaewon121 Sep 26, 2023
2f88cc4
refactor: 사용하지 않는 mdc토큰 제거
chaewon121 Sep 26, 2023
2d39e56
refactor: 로깅 전략 변경에 따른 코드 수정
chaewon121 Sep 26, 2023
504420b
refactor: xml파일에서 mdc 출력 삭제
chaewon121 Sep 27, 2023
b36a9af
refactor: 환경분리 및 패턴 수정
chaewon121 Sep 27, 2023
e1a1078
fix: 환경분리 오류 수정
chaewon121 Sep 27, 2023
d18af85
refactor: mdc 요소 추가
chaewon121 Sep 27, 2023
f2c4b92
chore: 워크플로우 수정
chaewon121 Sep 27, 2023
7a9a825
chore: 충돌해결
chaewon121 Sep 27, 2023
c22fd43
fix: 트렌젝션 테스트에 추가
chaewon121 Sep 27, 2023
71f7ee6
Merge branch 'feat/#303' of https://github.com/woowacourse-teams/2023…
dooboocookie Sep 28, 2023
b1dcaf5
Merge branch 'dev_backend' of https://github.com/woowacourse-teams/20…
dooboocookie Oct 2, 2023
75d4cc4
fix: 에러로그 출력 오류 수
chaewon121 Oct 3, 2023
377577b
refactor: info로그 수정
chaewon121 Oct 3, 2023
5726fab
refactor: warn로그 수정
chaewon121 Oct 3, 2023
41bee7b
refactor: error로그 수정
chaewon121 Oct 3, 2023
b77be5e
refactor: 사용하지 않는 enum 삭제
chaewon121 Oct 3, 2023
165ba62
refactor: 주석 제거
chaewon121 Oct 3, 2023
2e410df
refactor: 패키지 이동
chaewon121 Oct 3, 2023
20a078f
refactor: 사용하지 않는 코드 제거
chaewon121 Oct 4, 2023
6a2e7e5
refactor: warn 레벨 info 로 수정
chaewon121 Oct 4, 2023
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .idea/2023-naaga.iml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions .idea/vcs.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

20 changes: 11 additions & 9 deletions .idea/workspace.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 4 additions & 0 deletions backend/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,10 @@ dependencies {
implementation 'io.jsonwebtoken:jjwt-api:0.11.5'
implementation 'io.jsonwebtoken:jjwt-impl:0.11.5'
implementation 'io.jsonwebtoken:jjwt-jackson:0.11.5'

implementation 'ch.qos.logback.contrib:logback-jackson:0.1.5'
implementation 'ch.qos.logback.contrib:logback-json-classic:0.1.5'
implementation 'net.logstash.logback:logstash-logback-encoder:6.1'
}

tasks.named('test') {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package com.now.naaga.common.config;

import com.now.naaga.common.presentation.LogFilter;
import com.now.naaga.common.presentation.QueryCounter;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class FilterConfig {

private final QueryCounter queryCounter;

public FilterConfig(final QueryCounter queryCounter) {
this.queryCounter = queryCounter;
}

@Bean
public FilterRegistrationBean<LogFilter> logFilter() {
final LogFilter logFilter = new LogFilter(queryCounter);
return new FilterRegistrationBean<>(logFilter);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package com.now.naaga.common.config;

import com.now.naaga.common.presentation.QueryInspector;
import org.springframework.boot.autoconfigure.orm.jpa.HibernatePropertiesCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import static org.hibernate.cfg.AvailableSettings.STATEMENT_INSPECTOR;

@Configuration
public class HibernateConfig {

private final QueryInspector queryInspector;

public HibernateConfig(final QueryInspector queryInspector) {
this.queryInspector = queryInspector;
}

@Bean
public HibernatePropertiesCustomizer hibernatePropertiesCustomizer() {
return hibernateProperties -> hibernateProperties.put(STATEMENT_INSPECTOR, queryInspector);
}
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
package com.now.naaga.common.exception;

import jakarta.persistence.criteria.CriteriaBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
Expand All @@ -20,46 +19,41 @@ public class ControllerExceptionHandler {
public ResponseEntity<ExceptionResponse> handleBaseException(final BaseException e) {
final BaseExceptionType baseExceptionType = e.exceptionType();
final ExceptionResponse exceptionResponse = new ExceptionResponse(baseExceptionType.errorCode(), baseExceptionType.errorMessage());
log.warn("error = {}", exceptionResponse, e);

log.info("error = {}", exceptionResponse);

return ResponseEntity.status(baseExceptionType.httpStatus()).body(exceptionResponse);
}

@ExceptionHandler({
HttpMessageNotReadableException.class,
MethodArgumentNotValidException.class,
HttpMediaTypeNotSupportedException.class
})
HttpMediaTypeNotSupportedException.class})
public ResponseEntity<ExceptionResponse> handleTypeMismatchException(final Exception e) {
final CommonExceptionType commonExceptionType = CommonExceptionType.INVALID_REQUEST_BODY;
final ExceptionResponse exceptionResponse = new ExceptionResponse(commonExceptionType.errorCode(), commonExceptionType.errorMessage());
log.warn("error = {}", exceptionResponse, e);

log.info("error = {}", exceptionResponse);

return ResponseEntity.status(commonExceptionType.httpStatus()).body(exceptionResponse);
}

@ExceptionHandler(InternalException.class)
public ResponseEntity<ExceptionResponse> handleInternalException(final InternalException e){
public ResponseEntity<ExceptionResponse> handleInternalException(final InternalException e) {
final BaseExceptionType internalExceptionType = e.exceptionType();

// log.error("errorCode = {} \n message = {}",
// internalExceptionType.errorCode(),
// internalExceptionType.errorMessage());

log.error("errorCode = {} \n message = {} \n error = {}",
internalExceptionType.errorCode(),
internalExceptionType.errorMessage(),
e.getMessage() , e);
log.error(e.getMessage(), e);

final ExceptionResponse exceptionResponse = new ExceptionResponse(10000, "예기치 못한 오류입니다");
return ResponseEntity.status(internalExceptionType.httpStatus())
.body(exceptionResponse);
}

@ExceptionHandler(Exception.class)
public ResponseEntity<ExceptionResponse> handleException(final Exception e){
log.error("error = {}"+ e.getMessage() , e);
public ResponseEntity<ExceptionResponse> handleException(final Exception e) {
log.error(e.getMessage(), e);

final ExceptionResponse exceptionResponse = new ExceptionResponse(10000, "예기치 못한 오류입니다");
e.printStackTrace();
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body(exceptionResponse);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
package com.now.naaga.common.presentation;

import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;

import java.io.IOException;
import java.util.UUID;

import static com.now.naaga.common.presentation.MdcToken.*;

public class LogFilter implements Filter {

private static final String LOG_FORMAT = "uri: {}, method: {}, time: {}ms, queryCount: {}";

private final Logger log = LoggerFactory.getLogger(this.getClass().getSimpleName());
private final QueryCounter queryCounter;

public LogFilter(final QueryCounter queryCounter) {
this.queryCounter = queryCounter;
}

@Override
public void doFilter(final ServletRequest request,
final ServletResponse response,
final FilterChain chain)
throws IOException, ServletException {
queryCounter.init();

final long start = System.currentTimeMillis();
final HttpServletRequest httpServletRequest = (HttpServletRequest) request;
MDC.put(REQUEST_ID.getKey(), UUID.randomUUID().toString());

chain.doFilter(request, response);

final int queryCount = queryCounter.count();
log(start, queryCount, httpServletRequest);
queryCounter.close();
MDC.clear();
}

private void log(final long start,
final int queryCount,
final HttpServletRequest httpServletRequest) {
final long end = System.currentTimeMillis();
final long time = end - start;
log.info(LOG_FORMAT, httpServletRequest.getRequestURI(), httpServletRequest.getMethod(), time, queryCount);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package com.now.naaga.common.presentation;

public enum MdcToken {

REQUEST_ID("request_id")
;

private final String key;

MdcToken(final String key) {
this.key = key;
}

public String getKey() {
return key;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package com.now.naaga.common.presentation;

import org.springframework.stereotype.Component;

@Component
public class QueryCounter {

private static final int INITIAL_VALUE = 0;

private final ThreadLocal<Integer> count = new ThreadLocal<>();

public void increase() {
if (count.get() == null) {
init();
}
count.set(count.get() + 1);
}

public void init() {
count.set(INITIAL_VALUE);
}

public int count() {
return count.get();
}

public void close() {
count.remove();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
package com.now.naaga.common.presentation;

import org.hibernate.resource.jdbc.spi.StatementInspector;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;

import java.util.Objects;

@Component
public class QueryInspector implements StatementInspector {

private final QueryCounter queryCounter;

public QueryInspector(final QueryCounter queryCounter) {
this.queryCounter = queryCounter;
}

@Override
public String inspect(final String sql) {
if (isInRequestScope()) {
queryCounter.increase();
}
return sql;
}

private boolean isInRequestScope() {
return Objects.nonNull(RequestContextHolder.getRequestAttributes());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,8 @@

import com.now.naaga.game.domain.EndType;
import com.now.naaga.game.domain.Game;
import com.now.naaga.game.domain.GameStatus;
import com.now.naaga.gameresult.exception.GameResultException;
import com.now.naaga.gameresult.exception.GameResultExceptionType;
import com.now.naaga.place.domain.Position;

import static com.now.naaga.game.domain.GameStatus.IN_PROGRESS;

public enum ResultType {

SUCCESS,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,6 @@ public ResponseEntity<RankResponse> findMyRank(@Auth final PlayerRequest playerR
public ResponseEntity<List<RankResponse>> findAllRank(@RequestParam(name = "sort-by") final String sortBy,
@RequestParam(name = "order") final String order) {
if (!sortBy.equalsIgnoreCase("RANK") || !order.equalsIgnoreCase("ASCENDING")) {
System.out.println("sortBy: "+sortBy);
throw new CommonException(INVALID_REQUEST_PARAMETERS);
}

Expand All @@ -48,4 +47,5 @@ public ResponseEntity<List<RankResponse>> findAllRank(@RequestParam(name = "sort
.collect(Collectors.toList());
return ResponseEntity.ok(rankResponseList);
}

}
4 changes: 2 additions & 2 deletions backend/src/main/resources/application.yml
Original file line number Diff line number Diff line change
Expand Up @@ -31,9 +31,9 @@ logging:

spring:
config:
import: classpath:security/application-prod.yml
import: classpath:security/application-local.yml
activate:
on-profile: prod
on-profile: local

---

Expand Down
8 changes: 0 additions & 8 deletions backend/src/main/resources/console-appender.xml

This file was deleted.

22 changes: 0 additions & 22 deletions backend/src/main/resources/db-file-appender.xml

This file was deleted.

Loading
Loading