1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
package com.yanzuoguang.log;
import com.yanzuoguang.util.exception.ExceptionHelper;
import com.yanzuoguang.util.helper.JsonHelper;
import com.yanzuoguang.util.helper.StringHelper;
import com.yanzuoguang.util.log.Log;
import com.yanzuoguang.util.vo.CloudConfig;
import com.yanzuoguang.util.vo.ResponseResult;
import org.springframework.stereotype.Component;
/**
* 写入日志
*
* @author 颜佐光
*/
@Component
public class AspectLogResult {
private final CloudConfig cloudConfig;
private final LogLocal logLocal;
private final LogString logString;
private final ResponseResult<String> responseDefault = ResponseResult.result("操作成功");
public AspectLogResult(CloudConfig cloudConfig, LogLocal logLocal, LogString logString) {
this.cloudConfig = cloudConfig;
this.logLocal = logLocal;
this.logString = logString;
}
/**
* 保存日志
*
* @param resultFrom 结果
* @param resultEx 异常结果
* @param log 内容
*/
public void responseLog(LogInfoVo log, Object resultFrom, Exception resultEx) {
if (log == null || StringHelper.isEmpty(log.getLogId())) {
return;
}
try {
log.setEnd(System.currentTimeMillis());
long useTime = log.getEnd() - log.getStart();
log.setUseTime((int) useTime);
if (resultEx != null) {
log.setStatus(LogInfoVo.STATUS_ERROR);
} else {
log.setStatus(LogInfoVo.STATUS_OK);
}
ResponseResult<?> responseResult = getJson(resultFrom, resultEx);
String json = JsonHelper.serialize(responseResult);
String result = logString.getMaxString(json);
log.setResult(result);
// 输出日志标记
boolean isLogCommon = log.isLogFlag() && this.cloudConfig.isLogCommon();
boolean isError = resultEx != null;
boolean isLogDisplay = isLogCommon || isError;
if (isLogDisplay) {
Log.error(log.getCls(), resultEx, "%s [ %s ] time %d ms, result: %s", log.getTag(), log.getUrl(), log.getUseTime(), log.getResult());
}
} catch (Exception e) {
ExceptionHelper.PrintError(AspectLogResult.class, e);
} finally {
// 输出请求结果
logLocal.result(log);
if (log.isLogFlag()) {
Log.threadCommit();
}
}
}
private ResponseResult<?> getJson(Object result, Exception resultEx) {
try {
// 处理结果
ResponseResult<?> responseResult;
if (result instanceof ResponseResult) {
responseResult = (ResponseResult<?>) result;
} else if (result != null) {
responseResult = ResponseResult.result(result);
} else if (resultEx != null) {
responseResult = ExceptionHelper.getError(resultEx);
} else {
responseResult = responseDefault;
}
return responseResult;
} catch (Exception e) {
ExceptionHelper.PrintError(AspectLogResult.class, e);
return ExceptionHelper.getError(e);
}
}
}