package cn.com.poc.common.aspect;

import cn.com.yict.framemax.core.i18n.I18nMessageException;
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.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.Date;


/**
 * @author Focan.Zhong
 */
@Aspect
@Component
public class ServiceLoggingAspect {
    
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Pointcut(value = "execution(* *..service.*Service.*(..))")
    public void serviceMethod() {
    }

    @Around("serviceMethod()")
    public Object serviceMethodAround(ProceedingJoinPoint pjp) throws Throwable {
        Date before = new Date();
        String methodName = pjp.getSignature().getName();
        Object object = pjp.getTarget();
        Object retVal = null;

        logger.info("[Class:{}][Method:{}][Start]", object.getClass(), methodName);
        long interval = 0;
        try {
            retVal = pjp.proceed();
        } catch (Throwable e) {
            logException(methodName, object, e);
        } finally {
            Date after = new Date();
            interval = after.getTime() - before.getTime();

            logger.info("[Class:{}][Method:{}][Interval:{}ms][End]", object.getClass(), methodName, interval);
        }

        return retVal;
    }

    private void logException(String methodName, Object object, Throwable e) throws Throwable {
        //业务层异常
        if (e instanceof I18nMessageException) {
            I18nMessageException be = (I18nMessageException) e;
            logger.info("[Class:{}][Method:{}][BizException:{}-{}]", object.getClass(), methodName, be.getErrorCode(), be.getMessage());
            //系統异常
        } else {
            logger.error("[Class:{}][Method:{}]Exception:{}", object.getClass(), methodName, e.getMessage());
        }

        throw e;
    }

}
