Spring AOP annotations way to achieve log management

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/TreeShu321/article/details/102555399

Introduction: Use annotations way to achieve log management, can make our program become clear, simple, and not a lot of business code mixed together.

Realization of ideas roughly divided into four points

  • Design log table and log type, write and Service logs Dao and achieve
  • Custom annotations, annotation number of attributes, attribute may identify the type of operation (what is done)
  • Writing aspects pointcut expressions using the above comments directly to the positioning method annotations,
  • Written notice, by locating method to acquire properties the above comments and notes, and then directly from the session, or to obtain information about the current logged-on user from the database, the final call logs Service logs after storage according to business process some log information

Design log table and the log will be omitted in this step may be designed according to their actual conditions

Custom annotation

BussLog

package com.sl.annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * @author shuliangzhao
 * @Title: BussLog
 * @ProjectName spring-boot-learn
 * @Description: TODO
 * @date 2019/10/14 20:06
 */
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface BussLog {
    /**
     * 业务的名称
     */
    String value() default "";
    

    /**
     * 是否将当前日志记录到数据库中
     */
    boolean save() default true;
}

BussLogAspect

package com.sl.aop;

import com.alibaba.fastjson.JSON;
import com.sl.annotation.BussLog;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
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.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.LinkedList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author shuliangzhao
 * @Title: BussLogAspect
 * @ProjectName spring-boot-learn
 * @Description: TODO
 * @date 2019/10/14 20:08
 */
@Aspect
@Component
@EnableAspectJAutoProxy
public class BussLogAspect {

    private static final Logger log = LoggerFactory.getLogger(BussLogAspect.class);

    @Pointcut(value = "@annotation(com.sl.annotation.BussLog)")
    public void pointcut() {
    }

    @Around("pointcut()")
    public Object writeLog(ProceedingJoinPoint point) throws Throwable {

        //先执行业务
        Object result = point.proceed();

        try {
            handle(point);
        } catch (Exception e) {
            log.error("日志记录出错!", e);
        }

        return result;
    }

    private void handle(ProceedingJoinPoint point) throws Exception {
        Method currentMethod = getMethod(point);
        //获取操作名称
        BussLog annotation = currentMethod.getAnnotation(BussLog.class);
        boolean save = annotation.save();
        String bussinessName = parseParams(point.getArgs(), annotation.value());

        log.info("{} | {} - {} {} - {}", bussinessName);
        if (!save) {
            return;
        }

    }

    private Method getMethod(JoinPoint point) throws NoSuchMethodException {
        Signature sig = point.getSignature();
        MethodSignature msig = (MethodSignature) sig;
        Object target = point.getTarget();
        return target.getClass().getMethod(msig.getName(), msig.getParameterTypes());
    }
    public String parseParams(Object[] params, String bussinessName) {
        if (bussinessName.contains("{") && bussinessName.contains("}")) {
            List<String> result = match(bussinessName, "(?<=\\{)(\\d+)");
            for (String s : result) {
                int index = Integer.parseInt(s);
                bussinessName = bussinessName.replaceAll("\\{" + index + "}", JSON.toJSONString(params[index - 1]));
            }
        }
        return bussinessName;
    }

    private static List<String> match(String str, String regex) {
        if (null == str) {
            return null;
        }
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(str);
        List<String> list = new LinkedList<>();
        while (matcher.find()) {
            list.add(matcher.group());
        }
        return list;
    }
}

Guess you like

Origin blog.csdn.net/TreeShu321/article/details/102555399