小言_互联网的博客

【实用教程】SpringBoot实现AOP日志打印

298人阅读  评论(0)
package cn.nuc.zp.aop;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Aspect
@Component
public class ApiLogAspect {
    private static Logger logger = LoggerFactory.getLogger(ApiLogAspect.class);

    private final ObjectMapper mapper;

    @Autowired
    public ApiLogAspect(ObjectMapper mapper) {
        this.mapper = mapper;
    }

    @Pointcut("execution(* cn.nuc.zp.controller..*.*(..))")
    public void apiLog() {

    }

    @Before("apiLog()")
    public void before(JoinPoint joinPoint) {
        for (Object object : joinPoint.getArgs()) {
            if (object instanceof MultipartFile
                    || object instanceof HttpServletRequest
                    || object instanceof HttpServletResponse
            ) {
                continue;
            }
            try {
                if (logger.isDebugEnabled()) {
                    logger.debug(
                            joinPoint.getTarget().getClass().getName() + "." + joinPoint.getSignature().getName()
                                    + " : request parameter : " + mapper.writeValueAsString(object)
                    );
                }
            } catch (Exception e) {
                logger.error("{}", e.getMessage());
            }
        }
    }

    @Around("apiLog()")
    public Object around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        long startTime = System.currentTimeMillis();
        Object response = proceedingJoinPoint.proceed();
        if (logger.isDebugEnabled()) {
            logger.debug("response parameter : " + mapper.writeValueAsString(response));
            logger.debug("Time-Consuming : {} ms", System.currentTimeMillis() - startTime);
        }
        return response;
    }
}

 


转载:https://blog.csdn.net/zpwangshisuifeng/article/details/100987046
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场