package com.elab.log.asepct;

import com.alibaba.fastjson.JSON;
import com.dianping.cat.Cat;
import com.dianping.cat.message.Transaction;
import com.elab.core.utils.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Method;

/**
 * DAO层执行拦截器
 *
 * @author : liukx
 * @create : 2018/7/4 14:38
 * @email : liukx@elab-plus.com
 */
public class CatDaoAscept {
    private final Logger logger = LoggerFactory.getLogger(CatAspect.class);

    public Object around(ProceedingJoinPoint pjp) throws Throwable {
        Transaction transaction = null;
        Object proceed = null;
        try {
            MethodSignature joinPointObject = (MethodSignature) pjp.getSignature();
            Method method = joinPointObject.getMethod();
            // 获取参数的名称
            Class<?>[] par = ((MethodSignature) pjp.getSignature()).getParameterTypes();
            String methodName = pjp.getSignature().getName();
            Class<?> classTarget = pjp.getTarget().getClass();
            Method objMethod = classTarget.getMethod(methodName, par);

            transaction = Cat.getProducer().newTransaction("SQL", joinPointObject.getDeclaringTypeName().concat(".").concat(objMethod.getName()));
            logger.debug(" 开始执行方法 " + method.getName() + " 参数:" + StringUtils.logOut(JSON.toJSONString(pjp.getArgs())));
            proceed = pjp.proceed();
            if (proceed != null) {
                logger.debug("结束执行方法 " + method.getName() + " 参数值 : " + StringUtils.logOut(JSON.toJSONString(proceed)));
            } else {
                logger.debug(" 结束执行方法 ... " + method.getName());
            }
            transaction.setStatus(Transaction.SUCCESS);
        } catch (Exception e) {
            logger.error("SQL ERROR", e);
            transaction.setStatus(e);
            throw e;
        } finally {
            transaction.complete();
        }
        return proceed;
    }
}
