1.//作用于方法的注解 @AutoLog("删除图书")
import java.lang.annotation.*;
//作用于方法的注解
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface AutoLog {
String value() default "";
}
2.日志插入
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.example.entity.Admin;
import com.example.entity.Log;
import com.example.service.LogService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
/**
-
处理切面的的“监控”
*/
@Component
@Aspect
public class LogAspect {@Resource
private LogService logService;@Around("@annotation(autoLog)")
public Object doAround(ProceedingJoinPoint joinPoint, AutoLog autoLog) throws Throwable{
// 操作内容,我们在注解里定义了value
String name = autoLog.value();
String time = DateUtil.now();
// 当前操作人
String username = "";
Admin user = JwtTokenUtils.getCurrentUser();
if (ObjectUtil.isNotEmpty(user)){
username = user.getName();
}
// 操作人ip
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
String ip = request.getRemoteAddr();Log log = new Log(null, name, time, username, ip); logService.add(log); Result result = (Result) joinPoint.proceed(); return result;
}
}