Spring aop打印日志

package mis.webapp.config;

import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import mis.shared.json.JsonUtil;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

@Aspect
@Slf4j
@Component
public class LogAspect {

    /**
     * 定义切入点 controller
     */
    @Pointcut("execution(public * mis.webapp.controller..*.*(..))")
    public void Pointcut() {
    }

    /**
     * 在切点之前织入
     */
    @Before("Pointcut()")
    public void doBefore(JoinPoint joinPoint) {
        try{
            Logger logger = LoggerFactory.getLogger(joinPoint.getSignature().getDeclaringType());
            ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            if (requestAttributes == null) {
                return;
            }
            HttpServletRequest request = requestAttributes.getRequest();
            logger.info("method:{},param:{}", request.getMethod(), JsonUtil.toJsonString(joinPoint.getArgs()));
        }catch (Exception e){
            log.error("aop doBefore异常", e);
        }
    }

}

你可能感兴趣的:(spring,java,后端)