> 文章列表 > Java之~ Aop自定义注解日志

Java之~ Aop自定义注解日志

Java之~ Aop自定义注解日志

大纲步骤:
一,创建需要记录的日志表,创建基础方法。(省略)
二,在需要加记录日志的方法上加Aop注解1,创建一个注解类,Aop中定义一个注解
import java.lang.annotation.*;
/*** http 请求第三方请求日志使用注解*/
@Target({ElementType.TYPE,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @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
@Slf4j
public class HttpLogAspect {@Autowiredprivate 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 + "()");//获取requestObject[] request = joinPoint.getArgs();//请求的参数dto.setRequestBody(JSONObject.toJSONString(request));//响应的结果String res = JSONObject.toJSONString(result);dto.setResponseResult(res);dto.setCostTime(time);.......//添加日志httpLogApi.insert(dto);}}

演示: