使用自定义注解和AOP实现日志记录

1、自定义注解

package com.dh1027.login.annotation;

import java.lang.annotation.*;

/**
 * 日志注解
 * Created by heyj2 on 2018/7/12.
 */
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface DHLog {
    public String logDescription();
}

2、日志切面

package com.dh1027.login.annotation;

import com.dh1027.login.controller.LoginController;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * 日志记录切面
 * Created by heyj2 on 2018/7/12.
 */
@Aspect
@Component
public class LoggerAdvice {
    private Logger logger = LoggerFactory.getLogger(LoginController.class);

    @Pointcut("execution(public * com.dh1027.login..*(..))")
    public void webLog() {
    }

    @Before("webLog() && @annotation(loggerManage)")
    public void addBeforeLogger(JoinPoint joinPoint, DHLog loggerManage) {
        LocalDateTime now = LocalDateTime.now();

        logger.info(now.toString()+"执行[" + loggerManage.logDescription() + "]开始");
        logger.info("执行的方法["+joinPoint.getSignature().toString()+"]");

        logger.info("参数["+parseParames(joinPoint.getArgs())+"]");

    }

    @AfterReturning(pointcut = "webLog() && @annotation(loggerManage)")
    public void addAfterReturningLogger(JoinPoint joinPoint, DHLog loggerManage) {
        LocalDateTime now = LocalDateTime.now();
        logger.info(now.toString()+"执行 [" + loggerManage.logDescription() + "] 结束");
    }

    @AfterThrowing(pointcut = "webLog() && @annotation(loggerManage)", throwing = "ex")
    public void addAfterThrowingLogger(JoinPoint joinPoint, DHLog loggerManage, Exception ex) {
        LocalDateTime now = LocalDateTime.now();
        logger.error(now.toString()+"执行 [" + loggerManage.logDescription() + "] 异常", ex);
    }

    private String parseParames(Object[] parames) {

        if (null == parames || parames.length <= 0) {
            return "";

        }
        StringBuffer param = new StringBuffer("传入参数 # 个:[ ");
        int i =0;
        for (Object obj : parames) {
            i++;
            if (i==1){
                param.append(obj.toString());
                continue;
            }
            param.append(" ,").append(obj.toString());
        }
        return param.append(" ]").toString().replace("#",String.valueOf(i));
    }

}

3、测试使用

package com.dh1027.login.controller;

import com.dh1027.login.annotation.DHLog;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * Created by heyj2 on 2018/6/5.
 */
@RestController
public class HelloWorldController {
    Logger logger = LoggerFactory.getLogger(LoginController.class);

    @RequestMapping("/hello")
    @DHLog(logDescription = "测试注解......")
    public String index() {
        logger.info("-----Hello World--------");
        return "Hello World";
    }
}

猜你喜欢

转载自blog.csdn.net/dh1027/article/details/81201220