springboot利用注解和aop记录操作日志,这种方式耦合低,通用性高,不废话,直接上代码
先创建注解
import com.haier.common.enums.ErrorTypeEnum;
import java.lang.annotation.*;
/**
* 记录错误信息
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface SaveErrorInfo {
/**
* 是否开启功能,默认开启
* @return
*/
boolean value() default true;
/**
* 错误类型
* @return
*/
ErrorTypeEnum type();
/**
* 最大重试次数
* @return
*/
int maxRetryNum() default 3;
}
aop拦截处理业务,并把错误信息保存
import com.aliyun.openservices.shade.com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;
import java.util.concurrent.CompletableFuture;
@Slf4j
@Aspect
@Component
public class SaveErrorInfoHandler {
@Autowired
private DocErrorInfoService docErrorInfoService;
@Autowired
@Qualifier("threadPoolTaskExecutor")
private ThreadPoolTaskExecutor threadPoolTaskExecutor;
@Around("@annotation(saveErrorInfo)")
public Object handle(ProceedingJoinPoint joinPoint, SaveErrorInfo saveErrorInfo) throws Throwable {
try {
return joinPoint.proceed();
} catch (Throwable e) {
if (!saveErrorInfo.value()) {
throw e;
}
String className = e.getClass().getSimpleName();
String errorInfo = className+":"+e.getMessage();
Object[] args = joinPoint.getArgs();
ErrorTypeEnum errorTypeEnum = saveErrorInfo.type();
CompletableFuture.runAsync(() -> this.saveErrorInfo(saveErrorInfo,errorInfo, args, errorTypeEnum), threadPoolTaskExecutor);
throw e;
}
}
private void saveErrorInfo(SaveErrorInfo saveErrorInfo,String errorInfo, Object[] args, ErrorTypeEnum errorTypeEnum) {
String argStr = null;
if (null != args) {
argStr = JSON.toJSONString(args);
}
DocErrorInfo docErrorInfo = new DocErrorInfo(errorTypeEnum, argStr, errorInfo, saveErrorInfo.maxRetryNum(), 0);
docErrorInfoService.save(docErrorInfo);
}
}