|
1
2
3
4
5
6
|
package com.huaheng.framework.aspectj;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.huaheng.common.utils.ServletUtils;
import com.huaheng.common.utils.StringUtils;
|
|
7
|
import com.huaheng.common.utils.security.ShiroUtils;
|
|
8
|
import com.huaheng.common.utils.spring.SpringUtils;
|
|
9
10
11
12
13
14
15
16
|
import com.huaheng.framework.aspectj.lang.annotation.ApiLogger;
import com.huaheng.framework.web.domain.AjaxResult;
import com.huaheng.pc.config.address.domain.Address;
import com.huaheng.pc.config.address.service.AddressService;
import com.huaheng.pc.monitor.apilog.domain.ApiLog;
import com.huaheng.pc.monitor.apilog.service.IApiLogService;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.aspectj.lang.ProceedingJoinPoint;
|
|
17
18
19
|
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
|
|
20
21
22
23
|
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
|
|
24
25
|
import org.springframework.http.HttpHeaders;
import org.springframework.scheduling.annotation.Async;
|
|
26
27
|
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Component;
|
|
28
29
|
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
|
|
30
31
32
33
34
35
36
37
38
|
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.*;
/**
* Api调用日志记录处理
|
|
39
|
*
|
|
40
41
42
43
|
* @author huaheng
*/
@Aspect
@Component
|
|
44
45
|
@EnableAsync
public class ApiLogAspect {
|
|
46
47
48
49
50
51
52
53
|
private static final Logger log = LoggerFactory.getLogger(ApiLogAspect.class);
private static IApiLogService apiLogService;
private static AddressService addressService;
@Autowired
|
|
54
|
public void setApiLogService(IApiLogService apiLogService) {
|
|
55
56
57
58
|
ApiLogAspect.apiLogService = apiLogService;
}
@Autowired
|
|
59
|
public void setAddressService(AddressService addressService) {
|
|
60
61
62
63
64
|
ApiLogAspect.addressService = addressService;
}
// 配置织入点
@Pointcut("@annotation(com.huaheng.framework.aspectj.lang.annotation.ApiLogger)")
|
|
65
|
public void logPointCut() {
|
|
66
67
68
|
}
@Around("logPointCut() && @annotation(apiLogger)")
|
|
69
70
|
public Object around(ProceedingJoinPoint point, ApiLogger apiLogger) throws Throwable {
if ("WMS".equalsIgnoreCase(apiLogger.from()))
|
|
71
|
//实际上静态方法上的Aop注解无法拦截到
|
|
72
73
74
75
76
|
return aroundWms2XXX(point, apiLogger);
else
return aroundXXX2Wms(point, apiLogger);
}
|
|
77
78
79
80
|
/**
* 处理xxx调用wms接口的日志
**/
private Object aroundXXX2Wms(ProceedingJoinPoint point, ApiLogger apiLogger) {
|
|
81
82
|
Object ret = null;
ApiLog log = initApiLog(apiLogger, point);
|
|
83
|
try {
|
|
84
|
ret = point.proceed();
|
|
85
|
} catch (Exception e) {
|
|
86
|
setApiLogException(log, e);
|
|
87
88
|
ret = AjaxResult.error(e.getMessage());
} finally {
|
|
89
90
91
92
93
|
finishApiLog(log, ret);
return ret;
}
}
|
|
94
95
96
97
|
/**
* 处理WMS调用xxx接口的日志
**/
private Object aroundWms2XXX(ProceedingJoinPoint point, ApiLogger apiLogger) {
|
|
98
99
100
101
102
103
104
|
Object ret = null;
ApiLog log = new ApiLog();
HttpURLConnection connection = null;
String body = null;
try {
|
|
105
|
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
|
|
106
107
|
connection = (HttpURLConnection) point.getArgs()[0];
body = (String) point.getArgs()[1];
|
|
108
|
initApiLog(connection, body, ShiroUtils.getWarehouseCode());
|
|
109
|
} catch (Exception e) {
|
|
110
111
112
|
}
|
|
113
|
try {
|
|
114
|
ret = point.proceed();
|
|
115
|
} catch (Exception e) {
|
|
116
117
|
setApiLogException(log, e);
throw e;
|
|
118
119
|
} finally {
if (ret != null) {
|
|
120
121
|
finishApiLog(log, connection, ret.toString());
}
|
|
122
123
124
125
|
return ret;
}
}
|
|
126
127
128
129
130
|
/**
* 记录WMS调用外接口的请求信息
* 在HttpUtils.bodypost方法中直接调用本类static方法
**/
public static ApiLog initApiLog(HttpURLConnection connection, String body, String warehouseCode) {
|
|
131
132
133
134
135
|
ApiLog log = new ApiLog();
try {
log.setApiMethod(connection.getRequestMethod());
log.setUrl(connection.getURL().toString());
log.setRequestTime(new Date());
|
|
136
|
parseUrl(log, connection.getURL(), warehouseCode);
|
|
137
138
139
140
141
142
143
144
145
146
147
|
//请求头
Set<String> keySet = connection.getRequestProperties().keySet();
ArrayList<String> headerList = new ArrayList<>();
Iterator<String> it = keySet.iterator();
while (it.hasNext()) {
String name = it.next();
String header = connection.getRequestProperty(name);
headerList.add(name + ": " + header);
}
|
|
148
|
log.setRequestHeader(org.apache.commons.lang3.StringUtils.join(headerList, "\n"));
|
|
149
|
log.setRequestBody(body);
|
|
150
|
} catch (Exception e) {
|
|
151
152
153
154
155
156
|
e.printStackTrace();
}
return log;
}
|
|
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
|
/**
* 记录WMS调用外接口的请求信息
* 在HttpUtils.bodypost方法中直接调用本类static方法
**/
public static ApiLog initApiLog(String Method, String url, String body, HttpHeaders headers, String warehouseCode) {
ApiLog log = new ApiLog();
try {
URL url1 = new URL(url);
log.setApiMethod(Method);
log.setUrl(url);
log.setRequestTime(new Date());
parseUrl(log, url1, warehouseCode);
//请求头
Set<String> keySet = headers.keySet();
ArrayList<String> headerList = new ArrayList<>();
Iterator<String> it = keySet.iterator();
while (it.hasNext()) {
String name = it.next();
String header = String.valueOf(headers.getContentType());
headerList.add(name + ": " + header);
}
log.setRequestHeader(org.apache.commons.lang3.StringUtils.join(headerList, "\n"));
log.setRequestBody(body);
} catch (Exception e) {
e.printStackTrace();
}
return log;
}
/**
* 根据url,从address表中判断调用的去向
**/
public static void parseUrl(ApiLog log, URL url, String warehouseCode) {
|
|
194
195
196
197
198
199
|
try {
String[] spList = url.toString().split("/");
String apiName = spList[spList.length - 1];
int index = url.toString().lastIndexOf(apiName);
String addUrl = url.toString().substring(0, index);
|
|
200
|
Address address = addressService.getAddressByUrl(url.toString(), warehouseCode);
|
|
201
202
203
|
log.setApiName(apiName);
log.setRequestFrom("WMS");
log.setResponseBy(address.getParam().toUpperCase());
|
|
204
|
} catch (Exception e) {
|
|
205
206
207
208
|
e.printStackTrace();
}
}
|
|
209
210
211
212
|
/**
* 记录响应头信息
**/
public static void finishApiLog(ApiLog log, HttpURLConnection connection, String body) {
|
|
213
214
215
216
217
218
219
220
221
222
223
|
try {
log.setResponseBody(body);
log.setResponseTime(new Date());
Long duration = log.getResponseTime().getTime() - log.getRequestTime().getTime();
log.setDuration(duration.intValue());
log.setHttpCode(String.valueOf(connection.getResponseCode()));
//响应头
Set<String> keyset = connection.getHeaderFields().keySet();
ArrayList<String> headerList = new ArrayList<>();
Iterator<String> it = keyset.iterator();
|
|
224
|
while (it.hasNext()) {
|
|
225
226
|
String name = it.next();
String header = connection.getHeaderField(name);
|
|
227
|
if (name == null || "".equals(name))
|
|
228
229
230
231
232
|
//第一行没有name
//HTTP/1.1 200 OK
headerList.add(header);
else
headerList.add(name + ": " + header);
|
|
233
234
235
|
}
log.setResponseHeader(org.apache.commons.lang3.StringUtils.join(headerList, "\n"));
AjaxResult json = JSON.parseObject(body, AjaxResult.class);
|
|
236
|
log.setRetCode(String.valueOf(json.getCode()));
|
|
237
|
} catch (Exception e) {
|
|
238
|
e.printStackTrace();
|
|
239
240
|
} finally {
SpringUtils.getBean(ApiLogAspect.class).saveApiLog(log);
|
|
241
242
243
|
}
}
|
|
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
|
/**
* 记录响应头信息
**/
public static void finishApiLog(ApiLog log, HttpHeaders headers, String body) {
try {
log.setResponseBody(body);
log.setResponseTime(new Date());
Long duration = log.getResponseTime().getTime() - log.getRequestTime().getTime();
log.setDuration(duration.intValue());
log.setHttpCode(String.valueOf(200));
//响应头
Set<String> keyset = headers.keySet();
ArrayList<String> headerList = new ArrayList<>();
Iterator<String> it = keyset.iterator();
while (it.hasNext()) {
String name = it.next();
String header = String.valueOf(headers.getContentType());
if (name == null || "".equals(name))
//第一行没有name
//HTTP/1.1 200 OK
headerList.add(header);
else
headerList.add(name + ": " + header);
}
log.setResponseHeader(org.apache.commons.lang3.StringUtils.join(headerList, "\n"));
AjaxResult json = JSON.parseObject(body, AjaxResult.class);
log.setRetCode(String.valueOf(json.getCode()));
} catch (Exception e) {
e.printStackTrace();
} finally {
SpringUtils.getBean(ApiLogAspect.class).saveApiLog(log);
}
}
private ApiLog initApiLog(ApiLogger apiLogger, ProceedingJoinPoint point) {
|
|
282
|
ApiLog log = new ApiLog();
|
|
283
|
try {
|
|
284
285
286
287
288
289
290
291
292
|
log.setRequestTime(new Date());
log.setRequestFrom(apiLogger.from());
log.setResponseBy(apiLogger.to());
log.setApiName(apiLogger.apiName());
HttpServletRequest request = ServletUtils.getRequest();
String qryStr = request.getQueryString();
String url = request.getRequestURL().toString();
|
|
293
|
if (StringUtils.isNotEmpty(qryStr))
|
|
294
295
296
297
298
299
300
301
302
303
304
|
url = url + "?" + qryStr;
log.setUrl(url);
log.setApiMethod(request.getMethod());
log.setIp(request.getRemoteAddr());
rebuildRequestHeader(log);
rebuildRequestBody(log, request);
//如果reqeust中取不到post参数,就从接口方法参数中取json对象
|
|
305
|
if (StringUtils.isEmpty(log.getRequestBody()))
|
|
306
307
|
rebuildRequestBody(log, point);
|
|
308
|
} catch (Exception e) {
|
|
309
310
311
312
313
314
|
e.printStackTrace();
}
return log;
}
|
|
315
|
private void finishApiLog(ApiLog log, Object ret) {
|
|
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
|
try {
rebuildResponseHeader(log);
rebuildResponseBody(log, ret);
log.setResponseTime(new Date());
Long duration = log.getResponseTime().getTime() - log.getRequestTime().getTime();
log.setDuration(duration.intValue());
HttpServletResponse resp = ServletUtils.getResponse();
log.setHttpCode(String.valueOf(resp.getStatus()));
if (ret instanceof AjaxResult) {
int retCode = ((AjaxResult) ret).getCode();
log.setRetCode(String.valueOf(retCode));
}
|
|
331
|
} catch (Exception e) {
|
|
332
|
e.printStackTrace();
|
|
333
|
} finally {
|
|
334
335
336
337
|
saveApiLog(log);
}
}
|
|
338
|
public static void setApiLogException(ApiLog log, Exception e) {
|
|
339
340
|
try {
String exception = ExceptionUtils.getFullStackTrace(e);
|
|
341
|
String shortExpInfo = e.getMessage() + "\n" + org.apache.commons.lang3.StringUtils.left(exception, 1000);
|
|
342
|
log.setException(shortExpInfo);
|
|
343
|
} catch (Exception ex) {
|
|
344
345
346
347
|
ex.printStackTrace();
}
}
|
|
348
|
private void rebuildRequestHeader(ApiLog log) {
|
|
349
350
351
352
|
try {
HttpServletRequest req = ServletUtils.getRequest();
Enumeration names = req.getHeaderNames();
ArrayList<String> headerList = new ArrayList<>();
|
|
353
354
|
while (names.hasMoreElements()) {
String name = (String) names.nextElement();
|
|
355
356
357
358
359
|
String header = req.getHeader(name);
headerList.add(name + ": " + header);
}
String headers = org.apache.commons.lang3.StringUtils.join(headerList, "\n");
log.setRequestHeader(headers);
|
|
360
|
} catch (Exception e) {
|
|
361
362
363
364
|
e.printStackTrace();
}
}
|
|
365
366
367
368
369
|
/**
* 先从post参数中构造request body
*/
private void rebuildRequestBody(ApiLog log, HttpServletRequest request) {
try {
|
|
370
371
372
|
Set<String> keySet = request.getParameterMap().keySet();
Iterator<String> it = keySet.iterator();
StringBuffer sbf = new StringBuffer();
|
|
373
|
while (it.hasNext()) {
|
|
374
375
376
|
String key = it.next();
String value = request.getParameter(key);
sbf.append(key).append("=").append(value);
|
|
377
|
if (it.hasNext())
|
|
378
379
380
|
sbf.append("&");
}
log.setRequestBody(sbf.toString());
|
|
381
|
} catch (Exception e) {
|
|
382
383
384
385
386
387
388
|
e.printStackTrace();
}
}
/**
* 根据接口中的参数构造request body
*/
|
|
389
|
private void rebuildRequestBody(ApiLog log, ProceedingJoinPoint point) {
|
|
390
391
392
393
394
395
396
397
398
399
400
401
402
|
try {
if (point.getArgs().length == 1) {
log.setRequestBody(JSONObject.toJSONString(point.getArgs()[0]));
return;
}
MethodSignature m = (MethodSignature) point.getSignature();
HashMap<String, Object> map = new HashMap<>();
Object[] args = point.getArgs();
for (int i = 0; i < m.getParameterNames().length; i++) {
String name = m.getParameterNames()[i];
// Class type = m.getParameterTypes()[i];
map.put(name, args[i]);
}
|
|
403
|
if (!map.isEmpty())
|
|
404
|
log.setRequestBody(JSONObject.toJSONString(map));
|
|
405
|
} catch (Exception e) {
|
|
406
407
408
409
|
e.printStackTrace();
}
}
|
|
410
|
private void rebuildResponseHeader(ApiLog log) {
|
|
411
412
413
414
415
|
try {
HttpServletResponse resp = ServletUtils.getResponse();
Collection names = resp.getHeaderNames();
ArrayList<String> headerList = new ArrayList<>();
Iterator<String> it = names.iterator();
|
|
416
|
while (it.hasNext()) {
|
|
417
418
419
420
421
422
|
String name = it.next();
String header = resp.getHeader(name);
headerList.add(name + ": " + header);
}
String headers = org.apache.commons.lang3.StringUtils.join(headerList, "\n");
log.setResponseHeader(headers);
|
|
423
|
} catch (Exception e) {
|
|
424
425
426
427
|
e.printStackTrace();
}
}
|
|
428
|
private void rebuildResponseBody(ApiLog log, Object ret) {
|
|
429
430
|
try {
log.setResponseBody(JSONObject.toJSON(ret).toString());
|
|
431
|
} catch (Exception e) {
|
|
432
433
434
435
|
e.printStackTrace();
}
}
|
|
436
437
438
|
@Async
public void saveApiLog(ApiLog log) {
try {
|
|
439
|
apiLogService.saveOrUpdate(log);
|
|
440
|
} catch (Exception e) {
|
|
441
442
443
444
|
e.printStackTrace();
}
}
}
|