首先编写一个自定义注解,值为操作的内容
/**
* 系统日志注解
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface SysLog {
String value() default "";
}
/**
* 系统日志
*/
@Aspect
@Component
public class SysLogAspect {
定义切面类,切注解
@Pointcut("@annotation(com.webworld.marlboro.ecp.base.annotation.SysLog)")
public void logPointCut() {
}
环绕切
@Around("logPointCut()")
public Object around(ProceedingJoinPoint point) throws Throwable {
long beginTime = System.currentTimeMillis();
//执行方法
Object result = point.proceed();
//执行时长(毫秒)
long time = System.currentTimeMillis() - beginTime;
//保存日志
saveUserLog(point, time);
return result;
}
private void saveUserLog(ProceedingJoinPoint joinPoint, long time) {
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Method method = signature.getMethod();
UserLog userLog = new UserLog();
SysLog syslog = method.getAnnotation(SysLog.class);
if (syslog != null) {
//注解上的描述
userLog.setOperation(syslog.value());
}
//请求的方法名
String className = joinPoint.getTarget().getClass().getName();
String methodName = signature.getName();
// 方法返回值
AnnotatedType annotatedReturnType = method.getAnnotatedReturnType();
Type returnType = annotatedReturnType.getType();
String returnTypeName = returnType.getTypeName();
//请求的参数
Object[] args = joinPoint.getArgs();
userLog.setMethod(returnTypeName + " " + className + "." + methodName + "(" + Arrays.toString(args) + ")");
try {
String params = new Gson().toJson(args[0]);
userLog.setParameters(params);
} catch (Exception e) {
}
//获取request
HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
//获取请求类型
String requestMethod = request.getMethod();
userLog.setRequestType(requestMethod);
//获取userAgent
String userAgent = request.getHeader("User-Agent");
userLog.setUserAgent(userAgent);
String requestURI = request.getRequestURI();
userLog.setUrl(requestURI);
//设置IP地址
userLog.setIp(IPUtils.getIpAddr(request));
Long userId = NumberUtils.createLong(StringUtils.valueOf(HttpContextUtils.getAttribute(SessionConstant.USER_ID)));
Long shopId = NumberUtils.createLong(StringUtils.valueOf(HttpContextUtils.getAttribute(SessionConstant.SHOP_ID)));
if (userId == null) {
String weChatOpenId = StringUtils.valueOf(HttpContextUtils.getAttribute(SessionConstant.WE_CHAT_OPEN_ID));
if (StringUtils.isNotBlank(weChatOpenId)) {
User user = userService.findByWeChatOpenId(weChatOpenId);
if (user != null) {
userId = user.getId();
Shop shop = shopService.findByUserId(userId);
shopId = shop == null ? null : shop.getId();
}
}
}
userLog.setUserId(userId);
userLog.setShopId(shopId);
userLog.setTime(time);
userLog.setRequestDate(new Date());
//保存系统日志
userLogService.save(userLog);
}
}
@SysLog("修改当前用户信息")
@PutMapping(value = "/current/info")
public Result updateUserInfo(@RequestBody UserVo userVo) throws ParseException {
}
控制层加上SysLog注解,觉可以实现用户日志的记录了