1
1
package devkor .ontime_back ;
2
2
3
+ import devkor .ontime_back .dto .RequestInfoDto ;
3
4
import devkor .ontime_back .entity .ApiLog ;
4
5
import devkor .ontime_back .repository .ApiLogRepository ;
5
6
import devkor .ontime_back .response .GeneralException ;
7
+ import devkor .ontime_back .service .ApiLogService ;
6
8
import jakarta .servlet .http .HttpServletRequest ;
9
+ import lombok .RequiredArgsConstructor ;
7
10
import lombok .extern .slf4j .Slf4j ;
8
11
import org .aspectj .lang .JoinPoint ;
9
12
import org .aspectj .lang .ProceedingJoinPoint ;
13
16
import org .aspectj .lang .annotation .Pointcut ;
14
17
import org .aspectj .lang .reflect .MethodSignature ;
15
18
import org .springframework .http .ResponseEntity ;
19
+ import org .springframework .security .access .AccessDeniedException ;
16
20
import org .springframework .security .core .Authentication ;
17
21
import org .springframework .security .core .context .SecurityContextHolder ;
18
22
import org .springframework .stereotype .Component ;
23
+ import org .springframework .web .bind .MethodArgumentNotValidException ;
19
24
import org .springframework .web .bind .annotation .PathVariable ;
20
25
import org .springframework .web .bind .annotation .RequestBody ;
21
26
import org .springframework .web .context .request .RequestContextHolder ;
22
27
import org .springframework .web .context .request .ServletRequestAttributes ;
23
28
24
29
import java .lang .annotation .Annotation ;
30
+ import java .util .Map ;
25
31
26
32
27
33
@ Slf4j
28
34
@ Aspect
29
35
@ Component
36
+ @ RequiredArgsConstructor
30
37
public class LoggingAspect {
31
38
32
- private final ApiLogRepository apiLogRepository ;
33
-
34
- public LoggingAspect (ApiLogRepository apiLogRepository ) {
35
- this .apiLogRepository = apiLogRepository ;
36
- }
37
-
39
+ private final ApiLogService apiLogService ;
40
+ private static final String NO_PARAMS = "No Params" ;
41
+ private static final String NO_BODY = "No Body" ;
38
42
39
43
@ Pointcut ("bean(*Controller)" )
40
44
private void allRequest () {}
41
45
42
46
@ Around ("allRequest()" )
43
47
public Object logRequest (ProceedingJoinPoint joinPoint ) throws Throwable {
44
-
45
- HttpServletRequest request = ((ServletRequestAttributes ) RequestContextHolder .currentRequestAttributes ()).getRequest ();
46
-
47
- // requestUrl
48
- String requestUrl = request .getRequestURI ();
49
- // requestMethod
50
- String requestMethod = request .getMethod ();
51
- // userId
52
- Authentication authentication = SecurityContextHolder .getContext ().getAuthentication ();
53
- String userId = (authentication != null && authentication .isAuthenticated ())
54
- ? authentication .getName () // 인증된 사용자의 이름 (주로 ID로 사용됨)
55
- : "Anonymous" ;
56
- // clientIp
57
- String clientIp = request .getRemoteAddr ();
48
+ RequestInfoDto requestInfoDto = extractRequestInfo ();
58
49
59
50
// requestTime
60
51
long beforeRequest = System .currentTimeMillis ();
@@ -91,21 +82,14 @@ public Object logRequest(ProceedingJoinPoint joinPoint) throws Throwable {
91
82
92
83
// 정상 요청 로그 저장
93
84
long timeTaken = System .currentTimeMillis () - beforeRequest ;
94
- ApiLog apiLog = ApiLog .builder ().
95
- requestUrl (requestUrl ).
96
- requestMethod (requestMethod ).
97
- userId (userId ).
98
- clientIp (clientIp ).
99
- responseStatus (responseStatus ).
100
- takenTime (timeTaken ).
101
- build ();
102
85
103
- apiLogRepository .save (apiLog );
86
+ ApiLog apiLog = buildApiLog (requestInfoDto , responseStatus , timeTaken );
87
+ apiLogService .saveLog (apiLog );
104
88
105
89
log .info ("[Request Log] requestUrl: {}, requestMethod: {}, userId: {}, clientIp: {}, pathVariable: {}, requestBody: {}, responseStatus: {}, timeTaken: {}" ,
106
- requestUrl , requestMethod , userId , clientIp ,
107
- pathVariable != null ? pathVariable : "No Params" ,
108
- requestBody != null ? requestBody : "No Body" ,
90
+ requestInfoDto . getRequestUrl (), requestInfoDto . getRequestMethod (), requestInfoDto . getUserId (), requestInfoDto . getClientIp () ,
91
+ pathVariable != null ? pathVariable : NO_PARAMS ,
92
+ requestBody != null ? requestBody : NO_BODY ,
109
93
responseStatus , timeTaken );
110
94
111
95
return result ;
@@ -117,19 +101,7 @@ public Object logRequest(ProceedingJoinPoint joinPoint) throws Throwable {
117
101
118
102
@ AfterThrowing (pointcut = "allRequest()" , throwing = "ex" )
119
103
public void logException (JoinPoint joinPoint , Exception ex ) {
120
- HttpServletRequest request = ((ServletRequestAttributes ) RequestContextHolder .currentRequestAttributes ()).getRequest ();
121
-
122
- // requestUrl
123
- String requestUrl = request .getRequestURI ();
124
- // requestMethod
125
- String requestMethod = request .getMethod ();
126
- // userId
127
- Authentication authentication = SecurityContextHolder .getContext ().getAuthentication ();
128
- String userId = (authentication != null && authentication .isAuthenticated ())
129
- ? authentication .getName () // 인증된 사용자의 이름 (주로 ID로 사용됨)
130
- : "Anonymous" ;
131
- // clientIp
132
- String clientIp = request .getRemoteAddr ();
104
+ RequestInfoDto requestInfoDto = extractRequestInfo ();
133
105
134
106
// exceptionName
135
107
String exceptionName ;
@@ -144,32 +116,44 @@ public void logException(JoinPoint joinPoint, Exception ex) {
144
116
int responseStatus = mapExceptionToStatusCode (ex );
145
117
146
118
log .error ("[Error Log] requestUrl: {}, requestMethod: {}, userId: {}, clientIp: {}, exception: {}, message: {}, responseStatus: {}" ,
147
- requestUrl , requestMethod , userId , clientIp , exceptionName , exceptionMessage , responseStatus );
148
-
149
- // DB에 에러 로그 저장
150
- ApiLog errorLog = ApiLog .builder ().
151
- requestUrl (requestUrl ).
152
- requestMethod (requestMethod ).
153
- userId (userId ).
154
- clientIp (clientIp ).
155
- responseStatus (responseStatus ).
156
- takenTime (0 ).
157
- build ();
158
- // 상태 코드와 시간은 예제로 설정
159
- apiLogRepository .save (errorLog );
119
+ requestInfoDto .getRequestUrl (), requestInfoDto .getRequestMethod (), requestInfoDto .getUserId (), requestInfoDto .getClientIp (), exceptionName , exceptionMessage , responseStatus );
120
+
121
+ ApiLog errorLog = buildApiLog (requestInfoDto , responseStatus , 0 );
122
+ apiLogService .saveLog (errorLog );
123
+ }
124
+
125
+ // requestinfo 추출
126
+ private RequestInfoDto extractRequestInfo () {
127
+ HttpServletRequest request = ((ServletRequestAttributes ) RequestContextHolder .currentRequestAttributes ()).getRequest ();
128
+
129
+ String requestUrl = request .getRequestURI ();
130
+ String requestMethod = request .getMethod ();
131
+ Authentication authentication = SecurityContextHolder .getContext ().getAuthentication ();
132
+ String userId = (authentication != null && authentication .isAuthenticated ())
133
+ ? authentication .getName ()
134
+ : "Anonymous" ;
135
+ String clientIp = request .getRemoteAddr ();
136
+
137
+ return new RequestInfoDto (requestUrl , requestMethod , userId , clientIp );
138
+ }
139
+
140
+ // apilog 생성
141
+ private ApiLog buildApiLog (RequestInfoDto info , int responseStatus , long timeTaken ) {
142
+ return ApiLog .builder ()
143
+ .requestUrl (info .getRequestUrl ())
144
+ .requestMethod (info .getRequestMethod ())
145
+ .userId (info .getUserId ())
146
+ .clientIp (info .getClientIp ())
147
+ .responseStatus (responseStatus )
148
+ .takenTime (timeTaken )
149
+ .build ();
160
150
}
161
151
162
152
private int mapExceptionToStatusCode (Exception e ) {
163
- if (e instanceof IllegalArgumentException ) {
164
- return 400 ; // Bad Request
165
- } else if (e instanceof org .springframework .security .access .AccessDeniedException ) {
166
- return 403 ; // Forbidden
167
- } else if (e instanceof org .springframework .web .bind .MethodArgumentNotValidException ) {
168
- return 422 ; // Unprocessable Entity
169
- } else {
170
- return 500 ; // Internal Server Error
153
+ if (e instanceof GeneralException ge ) {
154
+ return ge .getErrorCode ().getCode ();
171
155
}
156
+ return 500 ;
172
157
}
173
158
174
-
175
159
}
0 commit comments