package com.tzld.longarticle.recommend.server.web;

import com.google.common.base.Stopwatch;
import com.tzld.longarticle.recommend.server.util.JSONUtils;
import com.tzld.longarticle.recommend.server.util.TraceUtils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @author dyp
 */
@Aspect
@Component
@Slf4j
public class ControllerAspect {

    @Around("execution(* com.tzld.longarticle.recommend.server.web.*Controller.*(..))")
    public Object around(ProceedingJoinPoint pjp) throws Throwable {
        TraceUtils.setMDC();

        String className = pjp.getTarget().getClass().getSimpleName();
        MethodSignature signature = (MethodSignature) pjp.getSignature();
        Stopwatch stopwatch = Stopwatch.createStarted();
        log.info("request className=[{}], method=[{}], param=[{}]", className, signature.getName(),
                JSONUtils.toJson(pjp.getArgs()));
        Object result = pjp.proceed();
        if (result != null && result instanceof String) {
            log.info("response result=[{}] cost=[{}]", result, stopwatch.stop().elapsed(TimeUnit.MILLISECONDS));
        } else {
            log.info("response result=[{}] cost=[{}]", JSONUtils.toJson(result), stopwatch.stop().elapsed(TimeUnit.MILLISECONDS));
        }

        TraceUtils.removeMDC();
        return result;
    }
}
