派生自 projectDept/qhighschool

yn147
2023-05-10 96286178ee1c257c130cb2ad964a781f36c4eee5
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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
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
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
package com.qxueyou.scc.base.handler;
 
import java.io.Serializable;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
 
import javax.servlet.http.HttpServletRequest;
 
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.core.annotation.Order;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.ParserContext;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
 
import com.alibaba.fastjson.JSON;
import com.qxueyou.scc.base.util.ClientUtils;
import com.qxueyou.scc.base.util.RequestClientUtils;
import com.qxueyou.scc.base.util.TraceUtils;
import com.qxueyou.scc.sys.model.SysLog;
import com.qxueyou.scc.sys.service.ISysLogService;
 
@Order(90)
@Aspect
@Component
public class QLogMonitor {
 
    private static final Logger logger = LogManager.getLogger("QLogMonitor");
 
    @Autowired
    ISysLogService logService;
 
    @Pointcut("execution(public * com.iqtogether.qxueyou..action.*Controller.*(..))")
    public void pointCutMethod() {
    }
 
    @Before("pointCutMethod()")
    public void doAfter(JoinPoint joinPoint) throws Throwable {
        ServletRequestAttributes servletWebRstRequest = null;
        HttpServletRequest request = null;
        MethodSignature methodSignature = null;
        String userAgent = null;
        String ip = null;
        String strContent = null;
        String strDesp = null;
        String strModule = "";
        QLog.LogType qLogType = QLog.LogType.SYS;
        short sLogType = -1;
        QLog qLog = null;
        try {
            methodSignature = (MethodSignature) joinPoint.getSignature();
            if (RequestContextHolder.getRequestAttributes() != null) {
                servletWebRstRequest = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
                request = servletWebRstRequest.getRequest();
                userAgent = request.getHeader("user-agent");
                if(StringUtils.isNotEmpty(userAgent) && userAgent.length()>255){
                    userAgent = userAgent.substring(0,255);
                }
                ip = RequestClientUtils.getRemoteIP(request);
            }
            
            qLog = AnnotationUtils.findAnnotation(methodSignature.getMethod(), QLog.class);
            if (qLog != null) {
                strContent = parserSpel(qLog.content(), joinPoint);
                strDesp = parserSpel(qLog.desp(), joinPoint);
                strModule = parserSpel(qLog.module(), joinPoint);
                qLogType = qLog.type();
            }
            // 默认为参数相关信息
            if (StringUtils.isEmpty(strContent)) {
                strContent = createDefaultContentInfo(joinPoint, methodSignature);
            }
            // 默认为请求的URI信息
            if(StringUtils.isEmpty(strDesp) && request!=null){
                strDesp =request.getRequestURI();
            }
            // 默认为:控制器模块注解value值+方法名
            if (StringUtils.isEmpty(strModule)) {
                strModule = createDefaultModuleInfo(joinPoint);
            }
            
            sLogType = (short) (QLog.LogType.SYS.equals(qLogType) ? 0 : 1);
 
            this.saveLog(strContent, strDesp, strModule.toUpperCase(), sLogType, ip,userAgent);
        } catch (Exception e) {
            logger.error("记录action操作日志发生异常!,errMsg:" + e.getMessage(), e);
        }
    }
 
    private String createDefaultModuleInfo(JoinPoint joinPoint) {
        String strModule = "";
        RequestMapping classReqMap = AnnotationUtils.findAnnotation(joinPoint.getTarget().getClass(),
                RequestMapping.class);
        if (classReqMap != null && classReqMap.value() != null && classReqMap.value().length > 0
                && StringUtils.isNotEmpty(classReqMap.value()[0])) {
            if (classReqMap.value()[0].startsWith("/")) {
                strModule = classReqMap.value()[0].substring(1);
            }
            if (StringUtils.isNotEmpty(strModule)) {
                strModule = strModule.concat("_").concat(joinPoint.getSignature().getName());
            } else {
                strModule = "ROOT".concat("_").concat(joinPoint.getSignature().getName());
            }
            strModule = strModule.replaceAll("/", "_");
        }
        
        if(StringUtils.isNotEmpty(strModule) && strModule.length()>64){
            strModule = strModule.substring(0, 64);
        }
        return strModule;
    }
 
    private String createDefaultContentInfo(JoinPoint joinPoint, MethodSignature methodSignature) {
        String strDesp="";
        if (joinPoint.getArgs() != null && joinPoint.getArgs().length > 0) {
            Map<String, Object> parmaMap = new HashMap<String, Object>(joinPoint.getArgs().length);
            for (int i = 0; i < joinPoint.getArgs().length; i++) {
                if (joinPoint.getArgs()[i] == null) {
                    parmaMap.put(methodSignature.getParameterNames()[i], "");
                } else {
                    if (this.checkParam(joinPoint.getArgs()[i].getClass())) {
                        parmaMap.put(methodSignature.getParameterNames()[i], joinPoint.getArgs()[i]);
                    }
                }
            }
            if (!parmaMap.isEmpty()) {
                strDesp = JSON.toJSONString(parmaMap);
                if (strDesp.length() > 250) {
                    strDesp = strDesp.substring(0, 250).concat("..");
                }
            }
        }
        return strDesp;
    }
 
    private void saveLog(String content, String desp, String module, short type, String ip,String userAgent) {
        SysLog lg = new SysLog();
        TraceUtils.setCreateActiveTrace(lg);
        lg.setUserId(ClientUtils.getUserId());
        lg.setUserName(ClientUtils.getUserName());
        lg.setDeleteFlag(Boolean.FALSE);
        lg.setContent(content);
        lg.setDesp(desp);
        lg.setModule(module);
        lg.setType(type);
        lg.setIp(ip);
        lg.setUserAgent(userAgent);
        logService.insertLog(lg);
    }
 
    private boolean checkParam(Class<?> paramClz) {
        if (paramClz.isPrimitive()) {
            return true;
        } else if (Byte.class.isAssignableFrom(paramClz)) {
            return true;
        } else if (Character.class.isAssignableFrom(paramClz)) {
            return true;
        } else if (Boolean.class.isAssignableFrom(paramClz)) {
            return true;
        } else if (Short.class.isAssignableFrom(paramClz)) {
            return true;
        } else if (Integer.class.isAssignableFrom(paramClz)) {
            return true;
        } else if (Long.class.isAssignableFrom(paramClz)) {
            return true;
        } else if (Float.class.isAssignableFrom(paramClz)) {
            return true;
        } else if (Double.class.isAssignableFrom(paramClz)) {
            return true;
        } else if (String.class.isAssignableFrom(paramClz)) {
            return true;
        } else if (Map.class.isAssignableFrom(paramClz)) {
            return true;
        } else if (List.class.isAssignableFrom(paramClz)) {
            return true;
        } else if (Collection.class.isAssignableFrom(paramClz)) {
            return true;
        } else if (paramClz.isArray()) {
            return true;
        } else if (Serializable.class.isAssignableFrom(paramClz)) {
            return true;
        }
        return false;
    }
 
    private String parserSpel(String strTemplate, JoinPoint joinPoint) {
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        ExpressionParser parser = new SpelExpressionParser();
        EvaluationContext ctx = new StandardEvaluationContext();
        // 设置变量
        if (joinPoint.getArgs() != null && joinPoint.getArgs().length > 0) {
            for (int i = 0; i < joinPoint.getArgs().length; i++) {
                if (joinPoint.getArgs()[i] != null && this.checkParam(joinPoint.getArgs()[i].getClass())) {
                    ctx.setVariable(methodSignature.getParameterNames()[i], joinPoint.getArgs()[i]);
                }
            }
        }
        String parsedString = parser.parseExpression(strTemplate, new ParserContext() {
            @Override
            public boolean isTemplate() {
                return true;
            }
 
            @Override
            public String getExpressionSuffix() {
                return "}";
            }
 
            @Override
            public String getExpressionPrefix() {
                return "{";
            }
        }).getValue(ctx, String.class);
        
        return parsedString;
    }
 
}