package com.jay.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* 日志注解(定义一个注解(@Interface),并添加目标注解指向方法、以及设置运行时有效)
* @author jay
*/
@Target({ ElementType.METHOD })//标志这个注解作用于方法
@Retention(RetentionPolicy.RUNTIME)//标志这个注解运行时有效
public @interface LogAnnotation {
String module() default "";
}
package com.jay.advice;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import com.jay.annotation.LogAnnotation;
import com.jay.model.SysLogs;
import com.jay.service.SysLogService;
import io.swagger.annotations.ApiOperation;
/**
* 统一日志处理
*/
@Aspect
@Component
public class LogAdvice {
@Autowired
private SysLogService logService;
//拦截LogAnnotation
@Around(value = "@annotation(com.jay.annotation.LogAnnotation)")
public Object logSave(ProceedingJoinPoint joinPoint) throws Throwable {
SysLogs sysLogs = new SysLogs();
sysLogs.setUser("admin"); // 设置当前登录用户
//获取注解上的方法
MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
String module = null;
//获取自定义日志注解上(@LogAnnotation)的返回值
LogAnnotation logAnnotation = methodSignature.getMethod().getDeclaredAnnotation(LogAnnotation.class);
module = logAnnotation.module();
//若定义的日志注解上没有设置返回值,则取swagger的@ApiOperation注解上设置的返回值
if (StringUtils.isEmpty(module)) {
ApiOperation apiOperation = methodSignature.getMethod().getDeclaredAnnotation(ApiOperation.class);
if (apiOperation != null) {
module = apiOperation.value();
}
}
if (StringUtils.isEmpty(module)) {
throw new RuntimeException("没有设置日志");
}
sysLogs.setModule(module);
try {
Object object = joinPoint.proceed();
sysLogs.setFlag(true);
return object;
} catch (Exception e) {
sysLogs.setFlag(false);
sysLogs.setRemark(e.getMessage());
throw e;
} finally {
if (sysLogs.getUser() != null) {
logService.save(sysLogs);
}
}
}
}