aop + annotation for unified logging

Keywords: Java Database

aop + annotation for unified logging

In development, we may need to log exceptions.Because exceptions are scattered, exceptions can occur for each service method, and many duplicate codes can occur and be difficult to maintain if we all handle them.This scenario should think of aop,
aop appears to solve such problems.

We can customize a comment to include in the way we want to log.Then use aop, the method of cutting the service layer, to determine if there is this comment on the method, and log processing if there is one.

Definition Notes:

package com.jerryl.auth.service.aop.log;  

import java.lang.annotation.*;  

/**  
 \* created by Demon, on 2018/7/22  
 */  

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

    String comment() default "";  
}  

Use aspect for cut

package com.jerryl.auth.service.aop.log;  

import org.aspectj.lang.ProceedingJoinPoint;  
import org.aspectj.lang.annotation.Around;  
import org.aspectj.lang.annotation.Aspect;  
import org.aspectj.lang.annotation.Pointcut;  
import org.aspectj.lang.reflect.MethodSignature;  
import org.springframework.stereotype.Component;  
import org.springframework.util.StopWatch;  

import java.lang.reflect.Method;  

/**  
 \* created by Demon, on 2018/7/22  
 */  

@Aspect  
@Component  
public class RecordLogAspect {  


    @Pointcut("execution(public * com.jerryl.auth.service..\*Manager.\*(..))")  
    public void addLog() {}  

    @Around("addLog()")  
    public Object addLog(ProceedingJoinPoint joinPoint) {  
        StopWatch stopWatch = new StopWatch();  
        stopWatch.start();  
        // Full class name  
        String typeName = joinPoint.getSignature().getDeclaringTypeName();  
        // Take Method Name  
        String methodName = joinPoint.getSignature().getName();  

        // Determine if there are log notes  
        MethodSignature joinPointObject = (MethodSignature) joinPoint.getSignature();  
        Method method = joinPointObject.getMethod();  
        boolean hasRecordLogAnnotation = method.isAnnotationPresent(RecordLog.class);  
        Object result = null;  

        try {  
            if (hasRecordLogAnnotation) {  
                result = joinPoint.proceed();  
                stopWatch.stop();  
                // Method Execution Time  
                long totalTimes = stopWatch.getTotalTimeMillis();  
            }  
        } catch (Throwable throwable) {  

            // Save method name, execution time, exception information to database table, record error log, method return  
        }  

        // Log normal logs of successful operations  
        return result;  
    }  
}  

If there are operations on the system that only super administrators need, they can also be solved by annotations and pre-notifications!

Posted by FraggleRock on Fri, 31 Jan 2020 12:51:30 -0800