通过aop优雅的打印接口出入参日志

maven依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-aop</artifactId>
</dependency>

代码:

@Component
@Aspect
@Slf4j
public class MethodLogAspect {


    @Pointcut( "execution(public * com.br..controller.*.*(..))" )
    public void expression() {}


    @Before(value = "expression()")
    public void beforeMethod() {

        ServletRequestAttributes sra = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = sra.getRequest();

        String servletPath = request.getServletPath();

        log.info("path: {} user: {}  args: {}",servletPath,ShiroUtils.getUserName(),JSONObject.toJSONString(request.getParameterMap()));
        
    }


    @AfterReturning(value="expression()" ,returning="result")
    public void afterReturning(Object result) {
        ServletRequestAttributes sra = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = sra.getRequest();

        String servletPath = request.getServletPath();
        
        log.info("path: {} user: {}  return: {}",servletPath,ShiroUtils.getUserName(), JSONObject.toJSONString(result));
        
    }

    @AfterThrowing(value="expression()" ,throwing="e")
    public void afterThrowing(JoinPoint joinPoint,Exception e) {
        String name=joinPoint.getSignature().getName();
        log.error("method {}  occur exception : {}",name,e.getMessage());
    }

}

项目中使用了shiro管理了登录用户的信息,ShiroUtils包含获取当前session中的用户信息的方法,可以根据自己的实际情况进行使用,附RequestContextHolder讲解 springmvc值RequestContextHolder分析

你可能感兴趣的:(分享,spring,boot)