package org.nl.acs.log;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
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.slf4j.MDC;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;


/**
 * @author: lyd
 * @description: 自定义日志切面:https://cloud.tencent.com/developer/article/1655923
 * @Date: 2022/10/10
 */
@Aspect
@Slf4j
@Component
public class LokiLogAspect {
    /**
     * 切到所有OperatorLog注解修饰的方法
     */
    @Pointcut("@annotation(org.nl.acs.log.LokiLog)")
    public void operatorLog() {
        // 空方法
    }

    /**
     * 利用@Around环绕增强
     *
     * @return
     */
    @Around("operatorLog()")
    public  Object around(ProceedingJoinPoint pjp) throws Throwable {
//        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
//        HttpServletRequest request = attributes.getRequest();
//        HttpServletResponse response = attributes.getResponse();

        Signature signature = pjp.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();
        LokiLog lokiLog = method.getAnnotation(LokiLog.class);
        // 获取描述信息
        LokiLogType logType = lokiLog.type();

        MDC.put("log_file_type", logType.getDesc());
        log.info("输入参数：" + JSONObject.toJSONString(pjp.getArgs()));

        Object proceed = pjp.proceed();

        log.info("返回参数：" + JSONObject.toJSONString(proceed));
        MDC.remove("log_file_type");
        return proceed;

    }
}
