自定义注解、使用切面编程实现日志打印

1、新建一个自定义注解类

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD}) //表示写在方法上的注解
public @interface ZjxLog {
}

2、@Pointcut定义切点(表示遇到自己设置的注解时先执行@Before下的方法,等方法全部运行完后再运行@After下的方法)

@Component
@Aspect
@Slf4j
public class ZjxLogAspect {
    @Pointcut("@annotation(com.yd.textspringboot.Aop.ZjxLog)")
    public void ZjxLogAspect() {}

    @Before("ZjxLogAspect()")
    public void beforeZjxLog(JoinPoint joinPoint){
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();

        String methodName = joinPoint.getSignature().getName();
        System.out.println("=========================== Method" + methodName + "() begin ===========================");

        //执行时间
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date d = new Date();
        String time = sdf.format(d);
        System.out.println("Time : " + time);
        //打印请求 URL
        System.out.println("URL : "+ request.getRequestURL());
        //打印 请求方法
        System.out.println("HTTP Method : "+ request.getMethod());
        //打印controller 的全路径以及执行方法
        System.out.println("class Method : "+ joinPoint.getSignature().getDeclaringTypeName()+ "." + ((MethodSignature) joinPoint.getSignature()).getName());
        //打印请求的 ip
        System.out.println("IP : "+ request.getRemoteHost());
        //打印请求入参
        System.out.println("Request Args : "+ JSON.toJSONString(joinPoint.getArgs()));
        System.out.println("==========================================================================");
    }

    @After("ZjxLogAspect()")
    public void afterZjxLog(JoinPoint joinPoint){
        String methodName = joinPoint.getSignature().getName();
        log.info("========================== Method" + methodName + "() end ======================================");
    }
}

3、最后再Controller下的方法上写上自定义注解(表示运行该方法之前会先运行上面代码的@before代码,再执行该方法,最后执行上面代码的@After的代码)

@RestController
public class textController {
    @GetMapping("text")
    @ZjxLog
    public ResultModel text(@RequestBody RequestModel requestModel){
        ResultModel resultModel = new ResultModel();
        resultModel.setMessage(requestModel.toString());
        return resultModel;
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值