大纲步骤:一,创建需要记录的日志表,创建基础方法。(省略)二,在需要加记录日志的方法上加Aop注解1,创建一个注解类,Aop中定义一个注解
import java.lang.annotation.*;/** * http 请求第三方请求日志使用注解 */@Target({ElementType.TYPE,ElementType.METHOD})@Retention(RetentionPolicy.RUNTIME)@Documentedpublic @interface HttpLog { //需要手动指定的枚举类HttpLogTypeEnum type();}
2,切面处理
import com.alibaba.fastjson.JSONArray;import com.alibaba.fastjson.JSONObject;import com.alibaba.fastjson.serializer.PropertyFilter;import lombok.extern.slf4j.Slf4j;import org.aspectj.lang.JoinPoint;import org.aspectj.lang.ProceedingJoinPoint;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.jeecg.common.constant.CommonConstant;import org.jeecg.common.util.SpringContextUtils;import org.springframework.core.LocalVariableTableParameterNameDiscoverer;import org.springframework.stereotype.Component;import org.springframework.validation.BindingResult;import org.springframework.web.multipart.MultipartFile;import javax.annotation.Resource;import javax.servlet.ServletRequest;import javax.servlet.ServletResponse;import javax.servlet.http.HttpServletRequest;import java.lang.reflect.Method;
/** * http第三方日志,切面处理类 * * @Author scott * @email jeecgos@163.com * @Date 2018年1月14日 */@Aspect@Component@Slf4jpublic class HttpLogAspect { @Autowired private SysThirdHttpLogApi httpLogApi; @Pointcut("@annotation(org.jeecg.common.aspect.annotation.HttpLog)") public void httpLogPointCut() { } @Around("httpLogPointCut()") public Object around(ProceedingJoinPoint point) throws Throwable { long beginTime = System.currentTimeMillis(); //执行方法 目标方法返回值 Object result = point.proceed(); //执行时长(毫秒) long time = System.currentTimeMillis() - beginTime; //保存http响应日志 saveSysHttpLog(point, time,result);// log.info(String.valueOf(result)); return result; }//处理数据,入库保存日志 private void saveSysHttpLog(ProceedingJoinPoint joinPoint, long time,Object result) { MethodSignature signature = (MethodSignature) joinPoint.getSignature(); Method method = signature.getMethod(); //获取注解类 HttpLog httpLog = method.getAnnotation(HttpLog.class); if (httpLog != null) { HttpLogDto dto = new HttpLogDto(); dto.setType(httpLog.type().name()); //方法名 //dto.setMethodType(httpLog.methodType().name()); //dto.setMethodName(httpLog.methodType().getDesc()); //请求的方法名 String className = joinPoint.getTarget().getClass().getName(); String methodName = signature.getName(); dto.setMethod(className + "." + methodName + "()"); //获取request Object[] request = joinPoint.getArgs(); //请求的参数 dto.setRequestBody(JSONObject.toJSONString(request)); //响应的结果 String res = JSONObject.toJSONString(result); dto.setResponseResult(res); dto.setCostTime(time);....... //添加日志 httpLogApi.insert(dto); } }
演示: