1+ package DiffLens .back_end .global .aop ;
2+
3+ import DiffLens .back_end .domain .members .service .auth .CurrentUserService ;
4+ import jakarta .servlet .http .HttpServletRequest ;
5+ import lombok .RequiredArgsConstructor ;
6+ import lombok .extern .slf4j .Slf4j ;
7+ import org .aspectj .lang .ProceedingJoinPoint ;
8+ import org .aspectj .lang .annotation .Around ;
9+ import org .aspectj .lang .annotation .Aspect ;
10+ import org .springframework .stereotype .Component ;
11+ import org .springframework .web .context .request .RequestContextHolder ;
12+ import org .springframework .web .context .request .ServletRequestAttributes ;
13+
14+ @ Aspect
15+ @ Component
16+ @ Slf4j
17+ @ RequiredArgsConstructor
18+ public class ApiRequestLogAspect {
19+
20+ private final CurrentUserService authService ;
21+
22+ /**
23+ * 전/후 처리 모두 가능
24+ * CommonPointcut.restControllerEndpoints() Pointcut 지정하여
25+ * API 호출 시 호출 전후로 로그 출력하도록 하는 Aspect
26+ */
27+ @ Around ("CommonPointCut.restControllerEndpoints()" )
28+ public Object logApiRequest (ProceedingJoinPoint jp ) throws Throwable {
29+ long start = System .currentTimeMillis ();
30+
31+ ServletRequestAttributes attrs = (ServletRequestAttributes ) RequestContextHolder .currentRequestAttributes ();
32+ HttpServletRequest request = attrs .getRequest ();
33+ String uri = request .getRequestURI ();
34+ String httpMethod = request .getMethod ();
35+
36+ Object currentUser = null ;
37+ try { currentUser = authService .getCurrentUser (); } catch (Exception ignored ) {}
38+
39+ String methodName = jp .getSignature ().getName ();
40+ String args = jp .getArgs () != null ? String .join (", " , java .util .Arrays .stream (jp .getArgs ())
41+ .map (String ::valueOf ).toArray (String []::new )) : "" ;
42+
43+ String userInfo = currentUser != null ? "[User: " + currentUser + "]" : "[User: Anonymous]" ;
44+ String requestInfo = "[" + httpMethod + ": " + uri + " - " + methodName + "(" + args + ")]" ;
45+
46+ log .info ("⏳ [API 호출 시작] {} {}" , userInfo , requestInfo );
47+
48+ try {
49+ Object result = jp .proceed ();
50+ long end = System .currentTimeMillis ();
51+ log .info ("✅ [API 호출 종료] {} {} - 실행시간: {}ms" , userInfo , requestInfo , (end - start ));
52+ return result ;
53+ } catch (Throwable ex ) {
54+ long end = System .currentTimeMillis ();
55+ log .error ("❌ [API 호출 예외] {} {} - 실행시간: {}ms - 예외: {}" , userInfo , requestInfo , (end - start ), ex .getMessage ());
56+ throw ex ; // 예외를 다시 던져서 컨트롤러에게 전달
57+ }
58+ }
59+
60+ }
0 commit comments