考虑单独的对每个方法做日志输出输入以及校验太麻烦了,就写了个aop去针对每个特定包下的内容进行处理,代码如下
package com.gaara.aop;
import com.alibaba.fastjson.JSONObject;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.Arrays;
/********************************
* Author Gaara *
* Version 1.0 *
* @ClassName RestLogAspect
* @Date 2021/4/25 上午11:00
* @Description TODO *
********************************/
@Slf4j
@Aspect
@Component
@AllArgsConstructor
public class RestLogAspect {
private HttpServletRequest request;
// 拦截包中定义的方法 不包含子包中的方法
@Pointcut("execution(public * com.gaara.controller.*.*(..))")
public void controllerPointCut(){}
// 拦截包中定义的方法,含子包
@Pointcut("execution(public * com.gaara.service..*.*(..))")
public void servicePointCut(){}
@Around("controllerPointCut()")
public Object controllerAround(ProceedingJoinPoint point)throws Throwable{
long t = System.currentTimeMillis();
Object ret;
try{
ret = point.proceed();
if (null == ret){
ret = "";
}
log.info("{} => {} => {}",request.getMethod(),request.getRequestURL().toString(), Arrays.toString(point.getArgs()));
log.info("耗时 == {}ms",(System.currentTimeMillis() - t));
}catch (Throwable e){
log.warn("{} => {} => {}",request.getMethod(),request.getRequestURL().toString(), e.getMessage());
log.warn("耗时 == {}ms",(System.currentTimeMillis() - t));
throw e;
}
return ret;
}
@Around("servicePointCut()")
public Object serviceAround(ProceedingJoinPoint point)throws Throwable{
try {
Signature signature = point.getSignature();
if (!(signature instanceof MethodSignature)){
return point.proceed();
}
// 获取基本信息
MethodSignature methodSignature = (MethodSignature) signature;
Method method = methodSignature.getMethod();
Class<?> clazz = method.getDeclaringClass();
Object[] args = point.getArgs();
String methodInfo = clazz.getName()+"#"+method.getName();
boolean b = !methodInfo.contains("#autoJoinClose") &&
!methodInfo.contains("#resetAndSendByState")&&
!methodInfo.contains("#xxx");
if (b){
// 入参
String params = null;
try {
params = JSONObject.toJSONStringWithDateFormat(args,"yyyy-MM-dd HH-mm-ss");
}catch (Exception e){
log.warn(e.getMessage());
}
log.info("开始方法【{}】调用,入参为:【{}】",methodInfo,params);
}
Object proceed = point.proceed();
//出参
String returnValue = null;
try {
returnValue = JSONObject.toJSONStringWithDateFormat(proceed,"yyyy-MM-dd HH-mm-ss");
}catch (Exception e){
log.warn(e.getMessage());
}
if (b){
log.info("【{}】方法结束调用,出参为:【{}】",methodInfo,returnValue);
}
return proceed;
}catch (Throwable e){
log.error(e.toString());
throw e;
}
}
}
网友评论