-
Notifications
You must be signed in to change notification settings - Fork 8
feat: API 성능 로깅, 쿼리 별 메트릭 전송 추가 #602
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
sukangpunch
wants to merge
19
commits into
solid-connection:develop
Choose a base branch
from
sukangpunch:feat/601-api-query-monitoring-and-logging
base: develop
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
19 commits
Select commit
Hold shift + click to select a range
bd909d5
feat: HTTP 요청/응답 로깅 필터 구현
sukangpunch ff145a8
feat: ExceptionHandler에 중복 로깅 방지 플래그 및 userId 로깅 추가
sukangpunch 88dee74
feat: API 수행시간 로깅 인터셉터 추가
sukangpunch 69ccdd6
feat: ApiPerf 인터셉터, Logging 필터 빈 등록
sukangpunch 222980c
refactor: logback 설정 변경
sukangpunch d49b83b
feat: 쿼리 별 수행시간 메트릭 모니터링 추가
sukangpunch d6793d3
refactor: 비효율적인 Time 빌더 생성 개선
sukangpunch db2c7f3
feat: 로깅을 위해 HttpServeletRequest 속성에 userId 추가
sukangpunch 5a11264
refactor: logback 설정 중 local은 console만 찍도록 수정
sukangpunch 1e4cfe2
refactor: FILE_PATTERN -> LOG_PATTERN 으로 수정
sukangpunch ac27d4f
test: TokenAuthenticationFilter에서 request에 userId 설정 검증 추가
sukangpunch 109a4e4
refacotr: 코드 래빗 리뷰사항 반영
sukangpunch 436256a
refactor: 리뷰 내용 반영
sukangpunch f12d81e
refactor: 로깅 시 민감한 쿼리 파라미터 마스킹
sukangpunch 69022fa
refactor: CustomExceptionHandler 원상복구
sukangpunch 4d1ffdc
refactor: 리뷰 사항 반영
sukangpunch 0f461b8
fix: decode를 두 번 하는 문제 수정
sukangpunch d346239
test: 로깅 관련 filter, interceptor 테스트 추가
sukangpunch dc04ef6
refactor: 코드래빗 리뷰사항 반영
sukangpunch File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
29 changes: 29 additions & 0 deletions
29
...main/java/com/example/solidconnection/common/config/datasource/DataSourceProxyConfig.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,29 @@ | ||
| package com.example.solidconnection.common.config.datasource; | ||
|
|
||
| import com.example.solidconnection.common.listener.QueryMetricsListener; | ||
| import javax.sql.DataSource; | ||
| import lombok.RequiredArgsConstructor; | ||
| import net.ttddyy.dsproxy.support.ProxyDataSourceBuilder; | ||
| import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties; | ||
| import org.springframework.context.annotation.Bean; | ||
| import org.springframework.context.annotation.Configuration; | ||
| import org.springframework.context.annotation.Primary; | ||
|
|
||
| @RequiredArgsConstructor | ||
| @Configuration | ||
| public class DataSourceProxyConfig { | ||
|
|
||
| private final QueryMetricsListener queryMetricsListener; | ||
|
|
||
| @Bean | ||
| @Primary | ||
| public DataSource proxyDataSource(DataSourceProperties props) { | ||
| DataSource dataSource = props.initializeDataSourceBuilder().build(); | ||
|
|
||
| return ProxyDataSourceBuilder | ||
| .create(dataSource) | ||
| .listener(queryMetricsListener) | ||
| .name("main") | ||
| .build(); | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
156 changes: 156 additions & 0 deletions
156
src/main/java/com/example/solidconnection/common/filter/HttpLoggingFilter.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,156 @@ | ||
| package com.example.solidconnection.common.filter; | ||
|
|
||
| import jakarta.servlet.FilterChain; | ||
| import jakarta.servlet.ServletException; | ||
| import jakarta.servlet.http.HttpServletRequest; | ||
| import jakarta.servlet.http.HttpServletResponse; | ||
| import java.io.IOException; | ||
| import java.net.URLDecoder; | ||
| import java.nio.charset.StandardCharsets; | ||
| import java.util.List; | ||
| import lombok.RequiredArgsConstructor; | ||
| import lombok.extern.slf4j.Slf4j; | ||
| import org.slf4j.MDC; | ||
| import org.springframework.http.HttpStatus; | ||
| import org.springframework.stereotype.Component; | ||
| import org.springframework.util.AntPathMatcher; | ||
| import org.springframework.web.filter.OncePerRequestFilter; | ||
|
|
||
| @Slf4j | ||
| @RequiredArgsConstructor | ||
| @Component | ||
| public class HttpLoggingFilter extends OncePerRequestFilter { | ||
|
|
||
| private static final AntPathMatcher PATH_MATCHER = new AntPathMatcher(); | ||
| private static final List<String> EXCLUDE_PATTERNS = List.of("/actuator/**"); | ||
| private static final List<String> EXCLUDE_QUERIES = List.of("token"); | ||
| private static final String MASK_VALUE = "****"; | ||
|
|
||
| @Override | ||
| protected void doFilterInternal( | ||
| HttpServletRequest request, | ||
| HttpServletResponse response, | ||
| FilterChain filterChain | ||
| ) throws ServletException, IOException { | ||
|
|
||
| // 1) traceId 부여 | ||
| String traceId = generateTraceId(); | ||
| MDC.put("traceId", traceId); | ||
|
|
||
| boolean excluded = isExcluded(request); | ||
|
|
||
| // 2) 로깅 제외 대상이면 그냥 통과 (traceId는 유지: 추후 하위 레이어 로그에도 붙음) | ||
| if (excluded) { | ||
| try { | ||
| filterChain.doFilter(request, response); | ||
| } finally { | ||
| MDC.clear(); | ||
| } | ||
| return; | ||
| } | ||
|
|
||
| printRequestUri(request); | ||
|
|
||
| try { | ||
| filterChain.doFilter(request, response); | ||
| printResponse(request, response); | ||
| } finally { | ||
| MDC.clear(); | ||
| } | ||
| } | ||
|
|
||
| private boolean isExcluded(HttpServletRequest req) { | ||
| String path = req.getRequestURI(); | ||
| for (String p : EXCLUDE_PATTERNS) { | ||
| if (PATH_MATCHER.match(p, path)) { | ||
| return true; | ||
| } | ||
| } | ||
| return false; | ||
| } | ||
|
|
||
| private String generateTraceId() { | ||
| return java.util.UUID.randomUUID().toString().replace("-", "").substring(0, 16); | ||
| } | ||
|
|
||
| private void printRequestUri(HttpServletRequest request) { | ||
| String methodType = request.getMethod(); | ||
| String uri = buildDecodedRequestUri(request); | ||
| log.info("[REQUEST] {} {}", methodType, uri); | ||
| } | ||
|
|
||
| private void printResponse( | ||
| HttpServletRequest request, | ||
| HttpServletResponse response | ||
| ) { | ||
| Long userId = (Long) request.getAttribute("userId"); | ||
| String uri = buildDecodedRequestUri(request); | ||
| HttpStatus status = HttpStatus.valueOf(response.getStatus()); | ||
|
|
||
| log.info("[RESPONSE] {} userId = {}, ({})", uri, userId, status); | ||
| } | ||
|
|
||
| private String buildDecodedRequestUri(HttpServletRequest request) { | ||
| String path = request.getRequestURI(); | ||
| String query = request.getQueryString(); | ||
|
|
||
| if(query == null || query.isBlank()){ | ||
| return path; | ||
| } | ||
|
|
||
| String decodedQuery = decodeQuery(query); | ||
| String maskedQuery = maskSensitiveParams(decodedQuery); | ||
|
|
||
| return path + "?" + maskedQuery; | ||
| } | ||
|
|
||
| private String decodeQuery(String rawQuery) { | ||
| if(rawQuery == null || rawQuery.isBlank()){ | ||
| return rawQuery; | ||
| } | ||
|
|
||
| try { | ||
| return URLDecoder.decode(rawQuery, StandardCharsets.UTF_8); | ||
| } catch (IllegalArgumentException e) { | ||
| log.warn("Query 디코딩 실패 parameter: {}, msg: {}", rawQuery, e.getMessage()); | ||
| return rawQuery; | ||
| } | ||
| } | ||
|
|
||
| private String maskSensitiveParams(String decodedQuery) { | ||
| String[] params = decodedQuery.split("&"); | ||
| StringBuilder maskedQuery = new StringBuilder(); | ||
|
|
||
| for(int i = 0; i < params.length; i++){ | ||
| String param = params[i]; | ||
|
|
||
| if(!param.contains("=")){ | ||
| maskedQuery.append(param); | ||
| }else{ | ||
| int equalIndex = param.indexOf("="); | ||
| String key = param.substring(0, equalIndex); | ||
|
|
||
| if(isSensitiveParam(key)){ | ||
| maskedQuery.append(key).append("=").append(MASK_VALUE); | ||
| }else{ | ||
| maskedQuery.append(param); | ||
| } | ||
| } | ||
|
|
||
| if(i < params.length - 1){ | ||
| maskedQuery.append("&"); | ||
| } | ||
| } | ||
|
|
||
| return maskedQuery.toString(); | ||
| } | ||
|
|
||
| private boolean isSensitiveParam(String paramKey) { | ||
| for (String sensitiveParam : EXCLUDE_QUERIES){ | ||
| if(sensitiveParam.equalsIgnoreCase(paramKey)){ | ||
| return true; | ||
| } | ||
| } | ||
| return false; | ||
| } | ||
| } |
67 changes: 67 additions & 0 deletions
67
src/main/java/com/example/solidconnection/common/interceptor/ApiPerformanceInterceptor.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,67 @@ | ||
| package com.example.solidconnection.common.interceptor; | ||
|
|
||
| import jakarta.servlet.http.HttpServletRequest; | ||
| import jakarta.servlet.http.HttpServletResponse; | ||
| import lombok.RequiredArgsConstructor; | ||
| import lombok.extern.slf4j.Slf4j; | ||
| import org.slf4j.Logger; | ||
| import org.slf4j.LoggerFactory; | ||
| import org.springframework.stereotype.Component; | ||
| import org.springframework.web.servlet.HandlerInterceptor; | ||
|
|
||
| @Slf4j | ||
| @RequiredArgsConstructor | ||
| @Component | ||
| public class ApiPerformanceInterceptor implements HandlerInterceptor { | ||
| private static final String START_TIME_ATTRIBUTE = "startTime"; | ||
| private static final String REQUEST_URI_ATTRIBUTE = "requestUri"; | ||
| private static final int RESPONSE_TIME_THRESHOLD = 3_000; | ||
| private static final Logger API_PERF = LoggerFactory.getLogger("API_PERF"); | ||
|
|
||
| @Override | ||
| public boolean preHandle( | ||
| HttpServletRequest request, | ||
| HttpServletResponse response, | ||
| Object handler | ||
| ) throws Exception { | ||
|
|
||
| long startTime = System.currentTimeMillis(); | ||
|
|
||
| request.setAttribute(START_TIME_ATTRIBUTE, startTime); | ||
| request.setAttribute(REQUEST_URI_ATTRIBUTE, request.getRequestURI()); | ||
|
|
||
| return true; | ||
| } | ||
|
|
||
| @Override | ||
| public void afterCompletion( | ||
| HttpServletRequest request, | ||
| HttpServletResponse response, | ||
| Object handler, | ||
| Exception ex | ||
| ) throws Exception { | ||
| Long startTime = (Long) request.getAttribute(START_TIME_ATTRIBUTE); | ||
| if(startTime == null) { | ||
| return; | ||
| } | ||
|
|
||
| long responseTime = System.currentTimeMillis() - startTime; | ||
|
|
||
| String uri = request.getRequestURI(); | ||
| String method = request.getMethod(); | ||
| int status = response.getStatus(); | ||
|
|
||
| if (responseTime > RESPONSE_TIME_THRESHOLD) { | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 개인적으론 if-else 구조가 로직을 이해하는 데 더 좋을 거 같습니다 !
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 수정하겠습니다! |
||
| API_PERF.warn( | ||
| "type=API_Performance method_type={} uri={} response_time={} status={}", | ||
| method, uri, responseTime, status | ||
| ); | ||
| } | ||
| else { | ||
| API_PERF.info( | ||
| "type=API_Performance method_type={} uri={} response_time={} status={}", | ||
| method, uri, responseTime, status | ||
| ); | ||
| } | ||
| } | ||
| } | ||
14 changes: 14 additions & 0 deletions
14
src/main/java/com/example/solidconnection/common/interceptor/RequestContext.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,14 @@ | ||
| package com.example.solidconnection.common.interceptor; | ||
|
|
||
| import lombok.Getter; | ||
|
|
||
| @Getter | ||
| public class RequestContext { | ||
| private final String httpMethod; | ||
| private final String bestMatchPath; | ||
|
|
||
| public RequestContext(String httpMethod, String bestMatchPath) { | ||
| this.httpMethod = httpMethod; | ||
| this.bestMatchPath = bestMatchPath; | ||
| } | ||
| } |
18 changes: 18 additions & 0 deletions
18
src/main/java/com/example/solidconnection/common/interceptor/RequestContextHolder.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,18 @@ | ||
| package com.example.solidconnection.common.interceptor; | ||
|
|
||
| public class RequestContextHolder { | ||
| private static final ThreadLocal<RequestContext> CONTEXT = new ThreadLocal<>(); | ||
|
|
||
| public static void initContext(RequestContext requestContext) { | ||
| CONTEXT.remove(); | ||
| CONTEXT.set(requestContext); | ||
| } | ||
|
|
||
| public static RequestContext getContext() { | ||
| return CONTEXT.get(); | ||
| } | ||
|
|
||
| public static void clear(){ | ||
| CONTEXT.remove(); | ||
| } | ||
| } |
36 changes: 36 additions & 0 deletions
36
src/main/java/com/example/solidconnection/common/interceptor/RequestContextInterceptor.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,36 @@ | ||
| package com.example.solidconnection.common.interceptor; | ||
|
|
||
| import static org.springframework.web.servlet.HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE; | ||
|
|
||
| import jakarta.servlet.http.HttpServletRequest; | ||
| import jakarta.servlet.http.HttpServletResponse; | ||
| import org.springframework.stereotype.Component; | ||
| import org.springframework.web.servlet.HandlerInterceptor; | ||
|
|
||
| @Component | ||
| public class RequestContextInterceptor implements HandlerInterceptor { | ||
|
|
||
| @Override | ||
| public boolean preHandle( | ||
| HttpServletRequest request, | ||
| HttpServletResponse response, | ||
| Object handler | ||
| ) { | ||
| String httpMethod = request.getMethod(); | ||
| String bestMatchPath = (String) request.getAttribute(BEST_MATCHING_PATTERN_ATTRIBUTE); | ||
|
|
||
| RequestContext context = new RequestContext(httpMethod, bestMatchPath); | ||
| RequestContextHolder.initContext(context); | ||
|
|
||
| return true; | ||
| } | ||
|
|
||
| @Override | ||
| public void afterCompletion( | ||
| HttpServletRequest request, | ||
| HttpServletResponse response, | ||
| Object handler, Exception ex | ||
| ) { | ||
| RequestContextHolder.clear(); | ||
| } | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.