Skip to content

Commit

Permalink
feat: 로깅시 요청마다 UUID 부여 (#686)
Browse files Browse the repository at this point in the history
  • Loading branch information
Gyaak authored Dec 6, 2024
1 parent ff50ef3 commit 3e30894
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 2 deletions.
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
package techpick.security.filter;

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

import org.slf4j.MDC;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

Expand All @@ -13,6 +15,12 @@
import techpick.core.util.CachedHttpServletRequest;
import techpick.core.util.RequestHolder;

/**
* 요청을 로깅하기 위한 Filter<br>
* UUID 를 MDC에 저장하여 Logback에서 활용<br>
* 요청 내용을 RequestHolder에 저장
* @author psh
* */
@Component
@RequiredArgsConstructor
public class RequestLoggingFilter extends OncePerRequestFilter {
Expand All @@ -23,12 +31,14 @@ public class RequestLoggingFilter extends OncePerRequestFilter {
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
FilterChain filterChain) throws ServletException, IOException {
try {
MDC.put("requestId", UUID.randomUUID().toString()); // for logback
CachedHttpServletRequest cachedRequest = new CachedHttpServletRequest(request);
requestHolder.setRequest(cachedRequest);
filterChain.doFilter(cachedRequest, response);
} finally {
// 요청이 마무리되면 무조건 ThreadLocal에 저장한 요청정보를 초기화
requestHolder.clearRequest();
MDC.remove("requestId"); // MDC 또한 ThreadLocal 기반이므로 반드시 해제해줘야함
}
}
}
9 changes: 7 additions & 2 deletions backend/techpick-api/src/main/resources/logback-spring.xml
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,8 @@
</rollingPolicy>
<!-- 로그를 남길 패턴 설정 -->
<encoder>
<pattern>[%d{yyyy-MM-dd HH:mm:ss}:%-3relative][%thread] %-5level %logger{35}[%line] - %msg%n</pattern>
<pattern>[%X{requestId}][%d{yyyy-MM-dd HH:mm:ss}:%-3relative] %-5level %logger{35} - %msg%n
</pattern>
</encoder>
</appender>

Expand All @@ -63,12 +64,16 @@
</rollingPolicy>
<!-- 로그를 남길 패턴 설정 -->
<encoder>
<pattern>[%d{yyyy-MM-dd HH:mm:ss}:%-3relative][%thread] %-5level %logger{35}[%line] - %msg%n</pattern>
<pattern>[%X{requestId}][%d{yyyy-MM-dd HH:mm:ss}:%-3relative] %-5level %logger{35} - %msg%n
</pattern>
</encoder>
</appender>

<!-- ``````````````````````` LOGGER SETTING ```````````````````````````` -->
<!-- (1) 프로젝트 전체 로그 설정 -->
<!-- <logger name="root" level="debug" additivity="false">-->
<!-- <appender-ref ref="CONSOLE"/>-->
<!-- </logger>-->
<logger name="techpick.api" level="info" additivity="false">
<appender-ref ref="CONSOLE"/>
<appender-ref ref="APP-LOG-FILE"/>
Expand Down

0 comments on commit 3e30894

Please sign in to comment.