spring AOP完成日志 + 面试解说

@Aspect
@Component
public class WebLogAspect {
    Logger logger = LoggerFactory.getLogger(WebLogAspect.class);

    @Around(value = "@annotation(org.springframework.web.bind.annotation.RequestMapping) || @annotation(org.springframework.web.bind.annotation.PostMapping)|| @annotation(org.springframework.web.bind.annotation.GetMapping)")
    public Object logAroundController(ProceedingJoinPoint point) throws Throwable {
        Object result = null;
        try {
            RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
            HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
            request.getParameterMap();
            //记录请求内容
            logger.info("Url:"+request.getRequestURI().toString());
            logger.info("HttpMethod:"+request.getMethod());
            logger.info("Ip:"+request.getRemoteAddr());
            logger.info("RequestParameter:"+ Arrays.toString(point.getArgs()));
            logger.info("---------------------------------------------------");
            //获取包名+类名 方法名
            logger.info(point.getSignature().getDeclaringTypeName()+"."+point.getSignature().getName());
            result = point.proceed();
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        return result;
    }

}

面试解说:AOP实现日志记录创建一个配置类配置加上Configuration注解和Aspect注解接着配置切入点就是给哪些方法进行添加日志的功能,这里我使用的是环绕通知并且加入切入点RequestMapping或者GetMapping或者PostMapping都添加日志功能,这个意思就是方法上有这个三个注解其中一个都会加上日志功能,接着使用RequestContextHolder获取HttpServletRequset请求这样就可以从该对象获取参数以及ip等参数然后进行保存进日志当中

  • 12
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值