Skip to content

Commit

Permalink
[BE] 요청 로그에 사용자 정보를 추가 (#298)
Browse files Browse the repository at this point in the history
* refactor: IP 주소 정보 삭제

* feat: 요청에 사용자 정보 추가

* fix: 예외 발생시 500응답 수정

* refactor: 패키지 이름 수정

* refactor: 역할에 따라 인터셉터 분

* refactor: userInfo 상수로 추출

* refactor: 인터셉터 등록 순서 명시적으로 지정

* refactor: 인터셉터 이름 수정

* refactor: 응답 로그에도 사용자 정보 추가

* refactor: MDC를 통해서 유저 정보를 가져오도록 수정
  • Loading branch information
ehBeak authored Aug 23, 2024
1 parent fc9a753 commit 820d310
Show file tree
Hide file tree
Showing 8 changed files with 126 additions and 80 deletions.
13 changes: 13 additions & 0 deletions backend/src/main/java/kr/momo/config/WebConfig.java
Original file line number Diff line number Diff line change
@@ -1,20 +1,33 @@
package kr.momo.config;

import java.util.List;
import kr.momo.config.interceptor.JwtInterceptor;
import kr.momo.config.interceptor.LoggingInterceptor;
import kr.momo.controller.auth.AuthArgumentResolver;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
@RequiredArgsConstructor
public class WebConfig implements WebMvcConfigurer {

private static final String BASE_URL = "/api/v1/**";

private final AuthArgumentResolver authArgumentResolver;
private final JwtInterceptor jwtInterceptor;
private final LoggingInterceptor loggingInterceptor;

@Override
public void addArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers) {
resolvers.add(authArgumentResolver);
}

@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(jwtInterceptor).addPathPatterns(BASE_URL).order(1);
registry.addInterceptor(loggingInterceptor).addPathPatterns(BASE_URL).order(2);
}
}
29 changes: 0 additions & 29 deletions backend/src/main/java/kr/momo/config/filter/FilterConfig.java

This file was deleted.

42 changes: 0 additions & 42 deletions backend/src/main/java/kr/momo/config/filter/LogFilter.java

This file was deleted.

Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
package kr.momo.config.interceptor;

import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.Optional;
import kr.momo.service.auth.JwtManager;
import lombok.RequiredArgsConstructor;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
@RequiredArgsConstructor
public class JwtInterceptor implements HandlerInterceptor {

public static final String USER_INFO = "userInfo";

private static final String ANONYMOUS = "ANONYMOUS";
private static final String ACCESS_TOKEN = "ACCESS_TOKEN";

private final JwtManager jwtManager;

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
Cookie[] cookies = request.getCookies();
String userInfo = getCookieValue(cookies).orElse(ANONYMOUS);
if (isLoginUser(userInfo)) {
userInfo = String.valueOf(jwtManager.extract(userInfo));
}
MDC.put(USER_INFO, userInfo);

return true;
}

private Optional<String> getCookieValue(Cookie[] cookies) {
if (cookies == null) {
return Optional.empty();
}

return Arrays.stream(cookies)
.filter(cookie -> ACCESS_TOKEN.equals(cookie.getName()))
.map(Cookie::getValue)
.findFirst();
}

private boolean isLoginUser(String token) {
return !ANONYMOUS.equals(token);
}
}
Original file line number Diff line number Diff line change
@@ -1,27 +1,39 @@
package kr.momo.config.filter;
package kr.momo.config.interceptor;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;

@Slf4j
@Component
@RequiredArgsConstructor
public class LogGenerator {

public void logRequest(String traceId, HttpServletRequest request) {
String httpMethod = request.getMethod();
String requestURI = request.getRequestURI();
String remoteAddr = request.getRemoteAddr();
String userInfo = MDC.get(JwtInterceptor.USER_INFO);

log.info("REQUEST [{}][{} {}][{}]", traceId, httpMethod, requestURI, remoteAddr);
log.info("REQUEST [{}][USERID:{}][{} {}]", traceId, userInfo, httpMethod, requestURI);
}

public void logResponse(String traceId, long duration, HttpServletRequest request, HttpServletResponse response) {
String httpMethod = request.getMethod();
String requestURI = request.getRequestURI();
String userInfo = MDC.get(JwtInterceptor.USER_INFO);
int status = response.getStatus();

log.info("RESPONSE [{}][{} {}][{} ms][Status: {}]", traceId, httpMethod, requestURI, duration, status);
log.info(
"RESPONSE [{}][USERID:{}][{} {}][{} ms][Status: {}]",
traceId,
userInfo,
httpMethod,
requestURI,
duration,
status
);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
package kr.momo.config.interceptor;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Slf4j
@RequiredArgsConstructor
@Component
public class LoggingInterceptor implements HandlerInterceptor {

public static final String TRACE_ID = "traceId";
private static final String START_TIME = "startTime";

private final TraceIdGenerator traceIdGenerator;
private final LogGenerator logGenerator;

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
String traceId = traceIdGenerator.generateShortUuid();
MDC.put(TRACE_ID, traceId);
logGenerator.logRequest(traceId, request);
request.setAttribute(START_TIME, System.currentTimeMillis());
return true;
}

@Override
public void afterCompletion(
HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex
) {
long startTime = (Long) request.getAttribute(START_TIME);
long duration = System.currentTimeMillis() - startTime;
String traceId = MDC.get(TRACE_ID);
logGenerator.logResponse(traceId, duration, request, response);
MDC.clear();
}
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package kr.momo.config.filter;
package kr.momo.config.interceptor;

import java.util.UUID;
import org.springframework.stereotype.Component;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
package kr.momo.exception;

import kr.momo.config.filter.LogFilter;
import kr.momo.config.interceptor.LoggingInterceptor;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.http.HttpStatus;
Expand All @@ -20,7 +20,7 @@ public class GlobalExceptionHandler {

@ExceptionHandler
public ProblemDetail handleMomoException(MomoException ex) {
String traceId = MDC.get(LogFilter.TRACE_ID);
String traceId = MDC.get(LoggingInterceptor.TRACE_ID);
log.warn(EXCEPTION_LOG_FORMAT, traceId, ex);

ProblemDetail problemDetail = ProblemDetail.forStatusAndDetail(ex.httpStatus(), ex.message());
Expand All @@ -29,7 +29,7 @@ public ProblemDetail handleMomoException(MomoException ex) {

@ExceptionHandler
public ProblemDetail handleMethodArgumentNotValidException(MethodArgumentNotValidException ex) {
String traceId = MDC.get(LogFilter.TRACE_ID);
String traceId = MDC.get(LoggingInterceptor.TRACE_ID);
log.warn(EXCEPTION_LOG_FORMAT, traceId, ex);

ProblemDetail problemDetail = ProblemDetail.forStatusAndDetail(
Expand All @@ -40,7 +40,7 @@ public ProblemDetail handleMethodArgumentNotValidException(MethodArgumentNotVali

@ExceptionHandler
public ProblemDetail handleInternalException(Exception ex) {
String traceId = MDC.get(LogFilter.TRACE_ID);
String traceId = MDC.get(LoggingInterceptor.TRACE_ID);
log.error(EXCEPTION_LOG_FORMAT, traceId, ex);

return ProblemDetail.forStatusAndDetail(HttpStatus.INTERNAL_SERVER_ERROR, INTERNAL_SERVER_ERROR_MESSAGE);
Expand Down

0 comments on commit 820d310

Please sign in to comment.