1.自定义日志监控注解,用于触发aop监控
@Documented
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Monitor {
String describe() default "";
}
2.编写AOP监控信息(获取信息后可以做记录存储到日志服务器(未实现))
@Aspect
@Component
@Slf4j
public class MonitorAop {
@Pointcut("@annotation(Monitor)")
public void monitor() {
}
@Around("monitor()")
public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
StringBuffer argsType = null;
Monitor annotation = null;
Object result = null;
try {
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
String urlStr = request.getRequestURL().toString();
Class<?> targetClassName = joinPoint.getTarget().getClass();
Signature signature = joinPoint.getSignature();
String typeStr = signature.getDeclaringType().toString().split(" ")[0];
MethodSignature methodSignature = (MethodSignature) signature;
Method method = methodSignature.getMethod();
annotation = method.getAnnotation(Monitor.class);
Object[] args = joinPoint.getArgs();
int length = args.length;
long begin = System.currentTimeMillis();
result = joinPoint.proceed();
long delay = System.currentTimeMillis() - begin;
log.debug("请求的url: " + urlStr);
log.debug("请求类/接口名: " + targetClassName.getSimpleName() + "(" + typeStr + ")");
log.debug("方法名: " + signature.getName());
if (StringUtils.isNotBlank(annotation.describe())) {
log.debug("方法监控描述: " + annotation.describe());
}
log.debug("参数个数: " + length);
if (length > 0) {
argsType = new StringBuffer(4);
for (Object object : args) {
argsType.append(object.getClass().getTypeName() + ",");
}
log.debug("参数类型:" + argsType);
}
log.debug("请求参数: " + getParameter(method, args));
log.debug("总耗时: " + delay + " ms");
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
private Object getParameter(Method method, Object[] args) {
List<Object> argList = new ArrayList<>(10);
Parameter[] parameters = method.getParameters();
for (int i = 0; i < parameters.length; i++) {
RequestBody requestBody = parameters[i].getAnnotation(RequestBody.class);
if (requestBody != null) {
argList.add(args[i]);
}
RequestParam requestParam = parameters[i].getAnnotation(RequestParam.class);
if (requestParam != null) {
Map<String, Object> map = new HashMap<>(16);
String key = parameters[i].getName();
if (!StringUtils.isEmpty(requestParam.value())) {
key = requestParam.value();
}
map.put(key, args[i]);
argList.add(map);
}
}
if (argList.size() == 0) {
return null;
}
if (argList.size() == 1) {
return argList.get(0);
}
return argList;
}
}
3.打开aop代理
aop:
proxy-target-class: true