-
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
Merged
sukangpunch
merged 21 commits into
solid-connection:develop
from
sukangpunch:feat/601-api-query-monitoring-and-logging
Jan 16, 2026
Merged
Changes from all commits
Commits
Show all changes
21 commits
Select commit
Hold shift + click to select a range
e2215e2
feat: HTTP 요청/응답 로깅 필터 구현
sukangpunch 609237a
feat: ExceptionHandler에 중복 로깅 방지 플래그 및 userId 로깅 추가
sukangpunch d265e3b
feat: API 수행시간 로깅 인터셉터 추가
sukangpunch 1653e7c
feat: ApiPerf 인터셉터, Logging 필터 빈 등록
sukangpunch a087a42
refactor: logback 설정 변경
sukangpunch 0c53761
feat: 쿼리 별 수행시간 메트릭 모니터링 추가
sukangpunch d83f7d4
refactor: 비효율적인 Time 빌더 생성 개선
sukangpunch ba07514
feat: 로깅을 위해 HttpServeletRequest 속성에 userId 추가
sukangpunch e057d2f
refactor: logback 설정 중 local은 console만 찍도록 수정
sukangpunch 239be9d
refactor: FILE_PATTERN -> LOG_PATTERN 으로 수정
sukangpunch d85041b
test: TokenAuthenticationFilter에서 request에 userId 설정 검증 추가
sukangpunch 42469af
refacotr: 코드 래빗 리뷰사항 반영
sukangpunch 7cb4aab
refactor: 리뷰 내용 반영
sukangpunch 3bf7425
refactor: 로깅 시 민감한 쿼리 파라미터 마스킹
sukangpunch 7857645
refactor: CustomExceptionHandler 원상복구
sukangpunch 3800a98
refactor: 리뷰 사항 반영
sukangpunch 545917a
fix: decode를 두 번 하는 문제 수정
sukangpunch 5af37c3
test: 로깅 관련 filter, interceptor 테스트 추가
sukangpunch 18c6a36
refactor: 코드래빗 리뷰사항 반영
sukangpunch 0ca2f74
refactor: 단위테스트에 TestContainer 어노테이션 제거
sukangpunch 9a77887
fix: conflict 해결
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🧩 Analysis chain
🏁 Script executed:
Repository: solid-connection/solid-connect-server
Length of output: 161
🏁 Script executed:
Repository: solid-connection/solid-connect-server
Length of output: 1025
🏁 Script executed:
Repository: solid-connection/solid-connect-server
Length of output: 7246
🏁 Script executed:
Repository: solid-connection/solid-connect-server
Length of output: 3189
HttpLoggingFilter의 중복 등록 문제를 반드시 수정해야 합니다.
검증 결과,
HttpLoggingFilter에@Component어노테이션이 적용되어 있으면서 동시에FilterRegistrationBean으로도 등록되고 있습니다. 이는 필터가 두 번 등록되어 실행될 수 있는 심각한 문제입니다.현재 상태
HttpLoggingFilter클래스:@Component어노테이션으로 자동 등록됨WebMvcConfig:FilterRegistrationBean으로 명시적 등록됨해결 방법
HttpLoggingFilter에서@Component어노테이션을 제거하거나WebMvcConfig의customHttpLoggingFilter()메서드를 제거하고 순서 제어가 필요하면 다른 방식 적용필터 우선순위를
Ordered.HIGHEST_PRECEDENCE로 제어하려는 의도가 있으므로,@Component를 제거하고FilterRegistrationBean방식만 유지하는 것을 권장합니다.🤖 Prompt for AI Agents