-
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
Changes from all commits
e2215e2
609237a
d265e3b
1653e7c
a087a42
0c53761
d83f7d4
ba07514
e057d2f
239be9d
d85041b
42469af
7cb4aab
3bf7425
7857645
3800a98
545917a
5af37c3
18c6a36
0ca2f74
9a77887
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| 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(); | ||
| } | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,11 +1,17 @@ | ||
| package com.example.solidconnection.common.config.web; | ||
|
|
||
| import com.example.solidconnection.common.interceptor.BannedUserInterceptor; | ||
| import com.example.solidconnection.common.filter.HttpLoggingFilter; | ||
| import com.example.solidconnection.common.interceptor.ApiPerformanceInterceptor; | ||
| import com.example.solidconnection.common.interceptor.RequestContextInterceptor; | ||
| import com.example.solidconnection.common.resolver.AuthorizedUserResolver; | ||
| import com.example.solidconnection.common.resolver.CustomPageableHandlerMethodArgumentResolver; | ||
| import java.util.List; | ||
| import lombok.RequiredArgsConstructor; | ||
| import org.springframework.boot.web.servlet.FilterRegistrationBean; | ||
| import org.springframework.context.annotation.Bean; | ||
| import org.springframework.context.annotation.Configuration; | ||
| import org.springframework.core.Ordered; | ||
| import org.springframework.web.method.support.HandlerMethodArgumentResolver; | ||
| import org.springframework.web.servlet.config.annotation.InterceptorRegistry; | ||
| import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; | ||
|
|
@@ -17,6 +23,9 @@ public class WebMvcConfig implements WebMvcConfigurer { | |
| private final AuthorizedUserResolver authorizedUserResolver; | ||
| private final CustomPageableHandlerMethodArgumentResolver customPageableHandlerMethodArgumentResolver; | ||
| private final BannedUserInterceptor bannedUserInterceptor; | ||
| private final HttpLoggingFilter httpLoggingFilter; | ||
| private final ApiPerformanceInterceptor apiPerformanceInterceptor; | ||
| private final RequestContextInterceptor requestContextInterceptor; | ||
|
|
||
| @Override | ||
| public void addArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers) { | ||
|
|
@@ -27,8 +36,24 @@ public void addArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers) | |
| } | ||
|
|
||
| @Override | ||
| public void addInterceptors(InterceptorRegistry registry) { | ||
| public void addInterceptors(InterceptorRegistry registry){ | ||
| registry.addInterceptor(apiPerformanceInterceptor) | ||
| .addPathPatterns("/**") | ||
| .excludePathPatterns("/actuator/**"); | ||
|
|
||
| registry.addInterceptor(requestContextInterceptor) | ||
| .addPathPatterns("/**") | ||
| .excludePathPatterns("/actuator/**"); | ||
|
|
||
| registry.addInterceptor(bannedUserInterceptor) | ||
| .addPathPatterns("/posts/**", "/comments/**", "/chats/**", "/boards/**"); | ||
| } | ||
coderabbitai[bot] marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| @Bean | ||
| public FilterRegistrationBean<HttpLoggingFilter> customHttpLoggingFilter() { | ||
| FilterRegistrationBean<HttpLoggingFilter> filterBean = new FilterRegistrationBean<>(); | ||
| filterBean.setFilter(httpLoggingFilter); | ||
| filterBean.setOrder(Ordered.HIGHEST_PRECEDENCE); | ||
| return filterBean; | ||
|
Comment on lines
+52
to
+57
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. 🧩 Analysis chain🏁 Script executed: #!/bin/bash
# Find HttpLoggingFilter class definition and check for annotations
find . -name "HttpLoggingFilter.java" -type f | head -20Repository: solid-connection/solid-connect-server Length of output: 161 🏁 Script executed: #!/bin/bash
# Search for `@Component` or `@WebFilter` annotations in HttpLoggingFilter
rg -n '@Component|@WebFilter' --type java -A 3 | grep -i 'httplogging' -A 3 -B 3Repository: solid-connection/solid-connect-server Length of output: 1025 🏁 Script executed: #!/bin/bash
# Check for all HttpLoggingFilter registrations
rg -n 'HttpLoggingFilter|FilterRegistrationBean.*HttpLoggingFilter' --type java -B 2 -A 5Repository: solid-connection/solid-connect-server Length of output: 7246 🏁 Script executed: #!/bin/bash
# Check WebMvcConfig.java for the relevant code
cat -n src/main/java/com/example/solidconnection/common/config/web/WebMvcConfig.java | head -70Repository: solid-connection/solid-connect-server Length of output: 3189 HttpLoggingFilter의 중복 등록 문제를 반드시 수정해야 합니다. 검증 결과,
필터 우선순위를 🤖 Prompt for AI Agents |
||
| } | ||
| } | ||
| 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; | ||
| } | ||
coderabbitai[bot] marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| 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; | ||
| } | ||
| } | ||
| 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 | ||
| ); | ||
| } | ||
| } | ||
| } | ||
| 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; | ||
| } | ||
| } |
| 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(); | ||
| } | ||
| } |
| 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); | ||
|
Comment on lines
+19
to
+23
Contributor
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. 발생 안할 거 같긴한데 여기서 예외 발생하면 clear가 안되니 try-catch로 catch에서 clear를 호출하는 게 안전할까요~?
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. 해당 내용을 알아보니까 afterCompletion은 내부적으로 finally 블록에서 호출되므로 return true 가 강제 된다면 무조건 호출 된다고 합니다(예외도 같이 afterCommit 으로 넘어가서 실행) |
||
|
|
||
| return true; | ||
| } | ||
|
|
||
| @Override | ||
| public void afterCompletion( | ||
| HttpServletRequest request, | ||
| HttpServletResponse response, | ||
| Object handler, Exception ex | ||
| ) { | ||
| RequestContextHolder.clear(); | ||
| } | ||
| } | ||
Uh oh!
There was an error while loading. Please reload this page.
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
🌐 Web query:
datasource-proxy net.ttddyy latest version Maven Central 2025💡 Result:
Latest Maven Central version: 1.11.0 (released July 14, 2025).
Maven dependency:
net.ttddyy
datasource-proxy
1.11.0
Sources: [Maven Repository (1.11.0)] [1], [javadoc.io (1.11.0)] [2], [Maven Central index/metadata] [3].
References
🌐 Web query:
datasource-micrometer net.ttddyy.observation latest version Maven Central 2025💡 Result:
The latest Maven Central version is net.ttddyy.observation:datasource-micrometer: 2.0.1. [1][2]
Sources:
🌐 Web query:
datasource-proxy 1.11.0 security vulnerability CVE💡 Result:
I found no public CVE that specifically affects the net.ttddyy datasource‑proxy 1.11.0 library itself. Maven listings for datasource‑proxy 1.11.0 show reported vulnerabilities coming from its dependencies (examples listed there include CVE-2025-68161, CVE-2024-38819, CVE-2023-6378), not a direct CVE for datasource‑proxy. [1]
Note: There is a separate, unrelated Grafana "datasource proxy" advisory (CVE-2025-3454) that affects Grafana’s server API — not the net.ttddyy datasource‑proxy Java library. Do not confuse the two. [2]
Sources:
References:
[1] https://mvnrepository.com/artifact/net.ttddyy/datasource-proxy/1.11.0
[2] https://grafana.com/security/security-advisories/cve-2025-3454/
🌐 Web query:
datasource-micrometer 1.2.0 security vulnerability CVE💡 Result:
I found no public CVE specifically affecting net.ttddyy.observation:datasource-micrometer version 1.2.0. The Maven listing for that artifact/version shows no CVE entry for the artifact itself. [1]
There are unrelated CVEs for other metric libraries (for example CVE-2020-1960 affecting Apache Flink's JMX reporter), but those do not apply to datasource-micrometer. [2][3]
If you want, I can:
Sources:
[1] mvnrepository — net.ttddyy.observation:datasource-micrometer 1.2.0.
[2] Micrometer security policy / advisories.
[3] NVD / GitLab advisory — CVE-2020-1960 (example of an unrelated metrics CVE).
데이터소스 프록시 의존성이 추가되었습니다. datasource-micrometer 버전 업그레이드를 권장합니다.
변경 내용:
datasource-proxy:1.11.0- 최신 버전이며, 쿼리 인터셉션을 위한 핵심 프록시 라이브러리입니다.datasource-micrometer:1.2.0- 최신 버전은 2.0.1이므로 업그레이드를 고려하세요. Micrometer와의 통합을 위한 라이브러리입니다.DataSourceProxyConfig 및 QueryMetricsListener와 연동되어 쿼리별 메트릭 수집을 지원합니다. 현재 datasource-micrometer는 1.2.0 사용 중이지만, 2.0.1이 최신 버전으로 이용 가능합니다. 특정 보안 취약점은 발견되지 않았으나, 최신 버전으로 업그레이드하면 개선 사항과 안정성을 함께 얻을 수 있습니다.
🤖 Prompt for AI Agents
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.
datasource-micrometer의존성이 내부적으로datasource-proxy를 포함하기에,datasource-proxy의존성은 제거해도 될 듯 합니다.버전은 1.2.x 그대로 사용하면 될 듯 합니다. 메이저 버전이 1인 경우 마이너 버전 2가 최신이고, 저희 Spring Boot 버전과 호환됩니다. 메이저 버전 2는 Spring Boot 4.x에서 지원하네요. [참고1], [참고2]
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.
@whqtker 정확한 지적 감사합니다! 제 분석이 잘못되었네요.
말씀하신 내용 정리:
중복 의존성 제거 필요
datasource-micrometer가 내부적으로datasource-proxy를 포함하고 있어, Line 72의implementation 'net.ttddyy:datasource-proxy:1.11.0'라인은 제거해도 됩니다.버전 1.2.0이 적절함
datasource-micrometer:1.2.0이 올바른 버전입니다.참고 자료 제공해주셔서 이해가 명확해졌습니다. 중복 의존성을 제거하면 의존성 관리가 더 깔끔해질 것 같습니다!
✏️ Learnings added