Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
e2215e2
feat: HTTP 요청/응답 로깅 필터 구현
sukangpunch Dec 31, 2025
609237a
feat: ExceptionHandler에 중복 로깅 방지 플래그 및 userId 로깅 추가
sukangpunch Dec 31, 2025
d265e3b
feat: API 수행시간 로깅 인터셉터 추가
sukangpunch Dec 31, 2025
1653e7c
feat: ApiPerf 인터셉터, Logging 필터 빈 등록
sukangpunch Jan 1, 2026
a087a42
refactor: logback 설정 변경
sukangpunch Jan 1, 2026
0c53761
feat: 쿼리 별 수행시간 메트릭 모니터링 추가
sukangpunch Jan 1, 2026
d83f7d4
refactor: 비효율적인 Time 빌더 생성 개선
sukangpunch Jan 1, 2026
ba07514
feat: 로깅을 위해 HttpServeletRequest 속성에 userId 추가
sukangpunch Jan 1, 2026
e057d2f
refactor: logback 설정 중 local은 console만 찍도록 수정
sukangpunch Jan 1, 2026
239be9d
refactor: FILE_PATTERN -> LOG_PATTERN 으로 수정
sukangpunch Jan 1, 2026
d85041b
test: TokenAuthenticationFilter에서 request에 userId 설정 검증 추가
sukangpunch Jan 2, 2026
42469af
refacotr: 코드 래빗 리뷰사항 반영
sukangpunch Jan 2, 2026
7cb4aab
refactor: 리뷰 내용 반영
sukangpunch Jan 3, 2026
3bf7425
refactor: 로깅 시 민감한 쿼리 파라미터 마스킹
sukangpunch Jan 6, 2026
7857645
refactor: CustomExceptionHandler 원상복구
sukangpunch Jan 6, 2026
3800a98
refactor: 리뷰 사항 반영
sukangpunch Jan 6, 2026
545917a
fix: decode를 두 번 하는 문제 수정
sukangpunch Jan 8, 2026
5af37c3
test: 로깅 관련 filter, interceptor 테스트 추가
sukangpunch Jan 8, 2026
18c6a36
refactor: 코드래빗 리뷰사항 반영
sukangpunch Jan 9, 2026
0ca2f74
refactor: 단위테스트에 TestContainer 어노테이션 제거
sukangpunch Jan 11, 2026
9a77887
fix: conflict 해결
sukangpunch Jan 16, 2026
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 build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,9 @@ dependencies {
implementation 'org.hibernate.validator:hibernate-validator'
implementation 'com.amazonaws:aws-java-sdk-s3:1.12.782'
implementation 'org.springframework.boot:spring-boot-starter-websocket'

// Database Proxy
implementation 'net.ttddyy.observation:datasource-micrometer:1.2.0'
}

tasks.named('test', Test) {
Expand Down
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;
Expand All @@ -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) {
Expand All @@ -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/**");
}

@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
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🔴 Critical

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Find HttpLoggingFilter class definition and check for annotations
find . -name "HttpLoggingFilter.java" -type f | head -20

Repository: 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 3

Repository: 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 5

Repository: 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 -70

Repository: solid-connection/solid-connect-server

Length of output: 3189


HttpLoggingFilter의 중복 등록 문제를 반드시 수정해야 합니다.

검증 결과, HttpLoggingFilter@Component 어노테이션이 적용되어 있으면서 동시에 FilterRegistrationBean으로도 등록되고 있습니다. 이는 필터가 두 번 등록되어 실행될 수 있는 심각한 문제입니다.

  1. 현재 상태

    • HttpLoggingFilter 클래스: @Component 어노테이션으로 자동 등록됨
    • WebMvcConfig: FilterRegistrationBean으로 명시적 등록됨
    • 결과: 동일한 필터가 이중 실행될 수 있음
  2. 해결 방법

    • HttpLoggingFilter에서 @Component 어노테이션을 제거하거나
    • WebMvcConfigcustomHttpLoggingFilter() 메서드를 제거하고 순서 제어가 필요하면 다른 방식 적용

필터 우선순위를 Ordered.HIGHEST_PRECEDENCE로 제어하려는 의도가 있으므로, @Component를 제거하고 FilterRegistrationBean 방식만 유지하는 것을 권장합니다.

🤖 Prompt for AI Agents
In
`@src/main/java/com/example/solidconnection/common/config/web/WebMvcConfig.java`
around lines 52 - 57, HttpLoggingFilter is being registered twice (as a
`@Component` and via the WebMvcConfig.customHttpLoggingFilter
FilterRegistrationBean), so remove the `@Component` annotation from the
HttpLoggingFilter class and keep the explicit FilterRegistrationBean
registration (customHttpLoggingFilter) with Ordered.HIGHEST_PRECEDENCE to
control ordering; ensure the HttpLoggingFilter bean instance used by
customHttpLoggingFilter is provided only via the registration path (not
component-scanned).

}
}
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;
}
}
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) {
Copy link
Member

Choose a reason for hiding this comment

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

개인적으론 if-else 구조가 로직을 이해하는 데 더 좋을 거 같습니다 !

Copy link
Contributor Author

Choose a reason for hiding this comment

The 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);

return true;
}

@Override
public void afterCompletion(
HttpServletRequest request,
HttpServletResponse response,
Object handler, Exception ex
) {
RequestContextHolder.clear();
}
}
Loading
Loading