Spring Boot:(四)统一日志处理

来源:互联网 发布:windows模拟器 编辑:程序博客网 时间:2024/05/18 01:12

并非只针对Spring Boot,如果你的项目用的是Spring MVC,做下简单的转换即可在你的项目中实现相同的功能

日志管理的实现

思路:

    在Service层中,涉及到大量业务逻辑操作,我们往往就需要在一个业务操作完成后(不管成败或失败),生成一条日志,并插入到数据库中。那么我们可以在这些涉及到业务操作的方法上使用一个自定义注解进行标记,同时将日志记录到注解中。再配合Spring的AOP功能,在监听到该方法执行之后,获取到注解内的日志信息,把这条日志插入到数据即可。

1、自定义注解

这里我们自定义一个日志注解,该注解中的logStr属性将用来保存日志信息。自定义注解代码如下:

@Retention(RetentionPolicy.RUNTIME)@Target({ElementType.METHOD})@Inherited@Documentedpublic @interface Log {    String logStr() default "";}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

2、使用自定义注解

接着就是到Service层中,在需要使用到日志功能的方法上加上该注解。如果业务需求是在添加一个用户之后,记录一条日志,那只需要在添加用户的方法上加上这个自定义注解即可。代码如下:

@Servicepublic class UserService {    @Log(logStr = "添加一个用户")    public Result add(User user) {        return ResultUtils.success();    }}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

3、使用AOP统一处理日志

前面的自定义注解只是起到一个标记与存储日志的作用,接下来需要就该使用Spring的AOP功能,拦截方法的执行,通过反射获取到注解及注解中所包含的日志信息。

如果你不清楚怎么在Spring Boot中使用AOP功能,建议你去看上一篇文章

因为代码量不大,就不多废话了,直接贴出日志切面的完整代码,详细情况看代码中的注释:

@Component@Aspectpublic class LogAspect {    private Logger logger = LoggerFactory.getLogger(LogAspect.class);    // 设置切点表达式    @Pointcut("execution(* com.lqr.service..*(..))")    private void pointcut() {    }    // 方法后置切面    @After(value = "pointcut()")    public void After(JoinPoint joinPoint) throws NotFoundException, ClassNotFoundException {        // 拿到切点的类名、方法名、方法参数        String className = joinPoint.getTarget().getClass().getName();        String methodName = joinPoint.getSignature().getName();        Object[] args = joinPoint.getArgs();        // 反射加载切点类,遍历类中所有的方法        Class<?> targetClass = Class.forName(className);        Method[] methods = targetClass.getMethods();        for (Method method : methods) {            // 如果遍历到类中的方法名与切点的方法名一致,并且参数个数也一致,就说明切点找到了            if (method.getName().equalsIgnoreCase(methodName)) {                Class<?>[] clazzs = method.getParameterTypes();                if (clazzs.length == args.length) {                    // 获取到切点上的注解                    Log logAnnotation = method.getAnnotation(Log.class);                    if (logAnnotation != null) {                        // 获取注解中的日志信息,并输出                        String logStr = logAnnotation.logStr();                        logger.error("获取日志:" + logStr);                        // 数据库记录操作...                        break;                    }                }            }        }    }}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42

4、验证

为了验证这种方式是否真的能拿到注解中携带的日志信息,这里创建一个Controller,代码如下:

@RestControllerpublic class UserController {    @Autowired    UserService mUserService;    @PostMapping("/add")    public Result add(User user) throws NotFoundException {        return mUserService.add(user);    }}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

使用postman访问接口,可以看到注解中的日志信息确实被拿到了。

你以为这样就结束了吗?不,这仅仅只是实现了日志功能,但称不上优雅,因为存在不方便的地方,下面就说下,如何对这种方式进一步优化,从而做到优雅的处理日志功能。

三、优化日志功能

1、分析

前面确确实实的使用自定义注解和AOP做到了日志功能,但存在什么问题呢?这个问题不是代码问题,而是业务功能问题。开发中可能有以下几种情况:

  1. 假设公司的业务是不仅仅只是记录某个用户使用该系统做了什么操作,还需要记录在操作的过程中出现过什么问题。
  2. 假设日志的内容,不可以在注解中写死,要可以在代码中自由设置日志信息。

简而言之,就是日志内容可以在代码中随意修改。这就有问题了,注解是静态侵入的,要怎么才能做到在代码中动态修改注解中的属性值呢?所幸,javassist可以帮我们做到这一点,下面就来看看,如果实现该功能。

javassist需要自己导入第三方依赖,如果你项目有使用到Spring Boot的模板功能(thymeleaf),则无须添加依赖。

2、完善与增强

1)封装AnnotationUtils

结合网上查阅到的资料,我对使用javassist动态修改方法上注解及查看注解中属性值的功能做了一个封装,工具类名为:AnnotationUtils(和Spring自带的一个类名字一样,注意不要在代码中导错包了),并使用了单例模式。代码如下:

/**  * @描述 注解中属性修改、查看工具 */public class AnnotationUtils {    private static AnnotationUtils mInstance;    public AnnotationUtils() {    }    public static AnnotationUtils get() {        if (mInstance == null) {            synchronized (AnnotationUtils.class) {                if (mInstance == null) {                    mInstance = new AnnotationUtils();                }            }        }        return mInstance;    }    /**     * 修改注解上的属性值     *     * @param className  当前类名     * @param methodName 当前方法名     * @param annoName   方法上的注解名     * @param fieldName  注解中的属性名     * @param fieldValue 注解中的属性值     * @throws NotFoundException     */    public void setAnnotatioinFieldValue(String className, String methodName, String annoName, String fieldName, String fieldValue) throws NotFoundException {        ClassPool classPool = ClassPool.getDefault();        CtClass ct = classPool.get(className);        CtMethod ctMethod = ct.getDeclaredMethod(methodName);        MethodInfo methodInfo = ctMethod.getMethodInfo();        ConstPool constPool = methodInfo.getConstPool();        AnnotationsAttribute attr = (AnnotationsAttribute) methodInfo.getAttribute(AnnotationsAttribute.visibleTag);        Annotation annotation = attr.getAnnotation(annoName);        if (annotation != null) {            annotation.addMemberValue(fieldName, new StringMemberValue(fieldValue, constPool));            attr.setAnnotation(annotation);            methodInfo.addAttribute(attr);        }    }    /**     * 获取注解中的属性值     *     * @param className  当前类名     * @param methodName 当前方法名     * @param annoName   方法上的注解名     * @param fieldName  注解中的属性名     * @return     * @throws NotFoundException     */    public String getAnnotatioinFieldValue(String className, String methodName, String annoName, String fieldName) throws NotFoundException {        ClassPool classPool = ClassPool.getDefault();        CtClass ct = classPool.get(className);        CtMethod ctMethod = ct.getDeclaredMethod(methodName);        MethodInfo methodInfo = ctMethod.getMethodInfo();        AnnotationsAttribute attr = (AnnotationsAttribute) methodInfo.getAttribute(AnnotationsAttribute.visibleTag);        String value = "";        if (attr != null) {            Annotation an = attr.getAnnotation(annoName);            if (an != null)                value = ((StringMemberValue) an.getMemberValue(fieldName)).getValue();        }        return value;    }}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74

2)封装LogUtils

通过上面的工具类(AnnotationUtils)虽然可以实现在代码中动态修改注解中的属性值的功能,但AnnotationUtils方法中需要的参数过多,这里对其做一层封装,不需要在代码中考虑类名、方法名的获取,方便开发。

/**  * @描述 日志修改工具 */public class LogUtils {    private static LogUtils mInstance;    private LogUtils() {    }    public static LogUtils get() {        if (mInstance == null) {            synchronized (LogUtils.class) {                if (mInstance == null) {                    mInstance = new LogUtils();                }            }        }        return mInstance;    }    public void setLog(String logStr) throws NotFoundException {        String className = Thread.currentThread().getStackTrace()[2].getClassName();        String methodName = Thread.currentThread().getStackTrace()[2].getMethodName();        AnnotationUtils.get().setAnnotatioinFieldValue(className, methodName, Log.class.getName(), "logStr", logStr);    }}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29

3)Service中根据情况动态修改日志信息

@Servicepublic class UserService {    @Log(logStr = "添加一个用户")    public Result add(User user) throws NotFoundException {        if (user.getAge() < 18) {            LogUtils.get().setLog("添加用户失败,因为用户未成年");            return ResultUtils.error("未成年不能注册");        }        if ("男".equalsIgnoreCase(user.getSex())) {            LogUtils.get().setLog("添加用户失败,因为用户是个男的");            return ResultUtils.error("男性不能注册");        }        LogUtils.get().setLog("添加用户成功,是一个" + user.getAge() + "岁的美少女");        return ResultUtils.success();    }}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21

4)修改日志切面

使用javassist修改过的注解属性值无法通过java反射正确静态获取,还需要借助javassist来动态获取,所以,LogAspect中的代码修改如下:

@Component@Aspectpublic class LogAspect {    private Logger logger = LoggerFactory.getLogger(LogAspect.class);    @Pointcut("execution(* com.lqr.service..*(..))")    private void pointcut() {    }    @After(value = "pointcut()")    public void After(JoinPoint joinPoint) throws NotFoundException, ClassNotFoundException {        String className = joinPoint.getTarget().getClass().getName();        String methodName = joinPoint.getSignature().getName();        String logStr = AnnotationUtils.get().getAnnotatioinFieldValue(className, methodName, Log.class.getName(), "logStr");        if (!StringUtils.isEmpty(logStr)) {            logger.error("获取日志:" + logStr);            // 数据库记录操作...        }    }}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22

3、验证

上面代码都编写完了,下面就验证下,是否可以根据业务情况动态注解中的属性值吧。

https://github.com/zhaoyulonggit/AopLog.git


原创粉丝点击