LogPrintAspect.java 2.59 KB
package com.diligrp.etrade.sentinel.aop;

import com.diligrp.etrade.core.annotation.ParamLogPrint;
import com.google.common.collect.Lists;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author dengwei
 * @version 1.0.0
 * @ClassName LogPrintAspect.java
 * @Description 方法参数打印切面
 * @date 2023-08-26 09:48
 */
@Component
@Aspect
public class LogPrintAspect {
    private final Logger LOG = LoggerFactory.getLogger(this.getClass());

    /**
     * 参数
     */
    @Before("@annotation(paramLogPrint)")
    public void paramLogPrint(JoinPoint joinPoint, ParamLogPrint paramLogPrint) {
        try {
            boolean print = paramLogPrint.print();
            if (!print) {
                return;
            }
            Signature signature = joinPoint.getSignature();
            String className = signature.getDeclaringTypeName() + "." + signature.getName();
            Object[] args = joinPoint.getArgs();

            List<Object> argsList = this.listArgs(args);

            Map<String, Object> logInfo = new LinkedHashMap<>(2);
            logInfo.put("method", className);
            logInfo.put("args", argsList);
            LOG.info("{}:{}", paramLogPrint.desc(), logInfo);
        } catch (Exception exception) {
            LOG.warn("param log error");
        }
    }

    /**
     * 参数列表
     *
     * @param args args
     * @return {@link List}<{@link Object}>
     */
    private List<Object> listArgs(Object[] args) {
        List<Object> argsList = Lists.newArrayListWithCapacity(args.length);
        for (Object arg : args) {
            Object param;
            if (arg instanceof HttpServletResponse) {
                param = HttpServletResponse.class.getSimpleName();
            } else if (arg instanceof HttpServletRequest) {
                param = HttpServletRequest.class.getSimpleName();
            } else if (arg instanceof MultipartFile) {
                param = MultipartFile.class.getSimpleName();
            } else {
                param = arg;
            }
            if (Objects.nonNull(param)) {
                argsList.add(param);
            }
        }
        return argsList;
    }
}