Spring自定义日志实现(5)——日志完成

经过前4部分的学习,我们很容易就能做一个日志的功能,代码如下:

注解类:

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface SelfLog {

    String aim() default "";

    String comment() default "";

}

切面类:

@Aspect
@Component
public class LogUtil {

    @Pointcut(value = "@annotation(com.example.demo.annoatinon.SelfLog)")
    public void log(){}


    @Around("log()")
    public void around(ProceedingJoinPoint pjp) throws Throwable {
        MethodSignature methodSignature = (MethodSignature)pjp.getSignature();
        Method method = methodSignature.getMethod();
        //获取注解
        SelfLog log = method.getAnnotation(SelfLog.class);
        //获取注解的参数
        System.out.println("aim:"+log.aim());
        System.out.println("comment:"+log.comment());
        //获取Request
        HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.currentRequestAttributes()).getRequest();
        ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();


        //获取请求的参数列表
        Map<String , String[]> parameterMap = request.getParameterMap();
        System.out.print("parameters: ");
        for(String key:parameterMap.keySet()){
            String[] parameters = parameterMap.get(key);
            for (String parameter: parameters){
                System.out.print(parameter+" ");

            }
        }
        System.out.println();
        //返回值
        String result = (String)pjp.proceed();
        System.out.println("result:"+result);
    }
}

Controller日志使用示例:

    @SelfLog(comment="HelloRedis IS GOOD", aim = "test")
    @RequestMapping("/helloRedis")
    public String HelloRedis(HttpServletRequest request, HttpServletResponse response, String parameter){
        redisUtil.set(parameter.getBytes(),"hi,i am redis".getBytes());
        return new String(redisUtil.get(parameter.getBytes()));
    }

这里只是将得到的信息打印出来,如果需要的话,可以将这些数据存入数据库或者做一些自己的逻辑

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值