自定义注解:
@Target(ElementType.METHOD)// 作用在方法上
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited // 子类可以继承此注解
public @interface OperationLog {
}
aop切面:
@Slf4j
@Aspect
@Component
public class OperationAspect {
@Autowired
private CorporaOperationLogMapper corporaOperationLogMapper;
private static final String OPERATOR_NAME = "operator-name";
private static final String OPERATOR_CODE = "operator-code";
@Pointcut("@annotation(com.dtranx.tools.corpora.business.annotations.OperationLog)")
private void pointcutAnnotation(){
}
public static void main(String[] args) {
System.out.println(Base64.getEncoder().encodeToString("苏红利".getBytes(StandardCharsets.UTF_8)));
}
@Around(value = "pointcutAnnotation()")
public Object around(ProceedingJoinPoint joinPoint) throws Exception{
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
String url = request.getRequestURI();
String operatorName = request.getHeader(OPERATOR_NAME);
String operatorCode = request.getHeader(OPERATOR_CODE);
Object[] args = joinPoint.getArgs();
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
ApiOperation annotation = signature.getMethod().getAnnotation(ApiOperation.class);
boolean result = false;
try {
Object res = joinPoint.proceed();
result = true;
return res;
} catch (Throwable e) {
log.error("接口请求失败:{}",url,e);
}finally {
try{
new ThreadExecutor<String>(CorporaOperationExecutor.executor).runSearch( CorporaOperationThread.builder()
.url(url)
.corporaOperationLogMapper(corporaOperationLogMapper)
.corporaOperationLog(CorporaOperationLog.builder()
.url(url)
.operationTime(new Date())
.params(JSON.toJSONString(args))
.operatorCode(operatorCode)
.operatorName(StringUtils.isNotEmpty(operatorName) ? new String(Base64.getDecoder().decode(operatorName.getBytes(StandardCharsets.UTF_8))):operatorName)
.urlDesc(annotation.value())
.result(result)
.build()).build());
}catch (Exception e){
}
}
throw new Exception("请求异常!");
}
}
OPERATOR_NAME和OPERATOR_CODE两个字段用于记录操作人和操作人编码,从请求头中获取。
使用方法:
在需要进行日志记录的操作方法上使用该自定义注解,并要求使用@ApiOperation注解(用于记录操作描述)。