1+ package refresh .acci .global .config ;
2+
3+ import jakarta .servlet .http .HttpServletRequest ;
4+ import lombok .extern .slf4j .Slf4j ;
5+ import org .aspectj .lang .ProceedingJoinPoint ;
6+ import org .aspectj .lang .annotation .Around ;
7+ import org .aspectj .lang .annotation .Aspect ;
8+ import org .aspectj .lang .annotation .Pointcut ;
9+ import org .springframework .security .core .Authentication ;
10+ import org .springframework .security .core .context .SecurityContextHolder ;
11+ import org .springframework .stereotype .Component ;
12+ import org .springframework .web .context .request .RequestContextHolder ;
13+ import org .springframework .web .context .request .ServletRequestAttributes ;
14+ import refresh .acci .domain .user .model .User ;
15+
16+ @ Slf4j
17+ @ Aspect
18+ @ Component
19+ public class LoggingConfig {
20+
21+ @ Pointcut ("within(@org.springframework.web.bind.annotation.RestController *)" )
22+ public void loggingPointcut () {}
23+
24+ @ Around ("loggingPointcut()" )
25+ public Object logApiRequest (ProceedingJoinPoint joinPoint ) throws Throwable {
26+ HttpServletRequest request = ((ServletRequestAttributes ) RequestContextHolder .getRequestAttributes ()).getRequest ();
27+
28+ String userId = getCurrentUserId (request );
29+ String method = request .getMethod ();
30+ String uri = request .getRequestURI ();
31+ long start = System .currentTimeMillis ();
32+
33+ try {
34+ return joinPoint .proceed ();
35+ } finally {
36+ long duration = System .currentTimeMillis () - start ;
37+ log .info ("user={} {} {} {}ms" , userId , method , uri , duration );
38+ }
39+ }
40+
41+ private String getCurrentUserId (HttpServletRequest request ) {
42+ Authentication authentication = SecurityContextHolder .getContext ().getAuthentication ();
43+
44+ if (authentication == null || authentication .getPrincipal () instanceof String ) {
45+ return request .getHeader ("X-Forwarded-For" );
46+ } else {
47+ if (authentication .getPrincipal () instanceof User user ) {
48+ return String .valueOf (user .getId ());
49+ }
50+ }
51+ return "anonymous" ;
52+ }
53+ }
0 commit comments