春AOPは、ログ管理を実現する方法を注釈します

免責事項:この記事はブロガーオリジナル記事です、続くBY-SAのCC 4.0を著作権契約、複製、元のソースのリンクと、この文を添付してください。
このリンク: https://blog.csdn.net/TreeShu321/article/details/102555399

記事のディレクトリ

はじめに:ログ管理を達成するために使用した注釈の方法は、私たちのプログラムは、単純な、明らかになって作ることができ、ビジネスのコードの多くは、一緒に混合されません。

アイデアの実現には、大きく4つのポイントに分け

  • デザインログテーブルとログの種類は、書き込みやサービスがダオをログに記録達成します
  • カスタム注釈、属性の注釈数は、属性は操作の種類を識別することができる(行われているもの)
  • 、測位方法の注釈に直接上記のコメントを使用して表現ポイントカット側面を書きます
  • 書面による通知は、性質上、コメントやメモを取得し、その後、直接セッションから、またはログオンしている現在のユーザのデータベースから情報を取得するための方法を配置することにより、最終的なコールが保存後のサービスログをログに記録し、ビジネスプロセスに応じて、いくつかのログ情報

デザインログテーブルとログは、この段階では省略されます彼らの実際の状況に応じて設計することができます

カスタム注釈

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;
    }
}

おすすめ

転載: blog.csdn.net/TreeShu321/article/details/102555399