1.springboot添加AOP依赖:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId> </dependency>
2.OperateLogAspect类
package com.towery.support; import com.towery.service.impl.DictServiceImpl; import com.towery.support.factory.LogTaskFactory; import com.towery.support.manager.LogExeManager; import com.towery.util.AuthLog; import com.towery.util.IpUtil; import org.apache.commons.lang3.StringUtils; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Pointcut; import org.aspectj.lang.reflect.MethodSignature; 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.servlet.http.HttpServletRequest; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Objects; @Aspect @Component public class OperateLogAspect { private static final Logger LOGGER = LoggerFactory.getLogger(OperateLogAspect.class); public OperateLogAspect(){ LOGGER.info("操作日志aop初始化"); }
//切入点为包含AuthLog注解的方法上 @Pointcut("@annotation(com.towery.util.AuthLog)") public void webInteceptor(){ } @Around("webInteceptor()") public Object around(ProceedingJoinPoint joinPoint) throws Throwable{ MethodSignature signature = (MethodSignature) joinPoint.getSignature(); Method method = signature.getMethod(); try{ AuthLog annotation = method.getAnnotation(AuthLog.class); //操作模块operation String module = null; //描述 String remark = null; if(annotation != null){ module = annotation.MODULE(); remark = annotation.REMARK(); } //请求方法名 //String methodName = signature.getName(); //请求参数 String[] parameterNames = ((MethodSignature) joinPoint.getSignature()).getParameterNames(); StringBuilder sb = null; if (Objects.nonNull(parameterNames)) { sb = new StringBuilder(); for (int i = 0; i < parameterNames.length; i++) { Object param = joinPoint.getArgs()[i] != null ? joinPoint.getArgs()[i] : ""; if (StringUtils.isNotEmpty(param.toString()) && !"request".equals(parameterNames[i]) && !"response".equals(parameterNames[i]) && !"modelMap".equals(parameterNames[i])) { if (param instanceof Integer) { sb.append(parameterNames[i] + ":" + param + "; "); } else if (param instanceof String) { sb.append(parameterNames[i] + ":" + param + "; "); } else if (param instanceof Double) { sb.append(parameterNames[i] + ":" + param + "; "); } else if (param instanceof Float) { sb.append(parameterNames[i] + ":" + param + "; "); } else if (param instanceof Long) { sb.append(parameterNames[i] + ":" + param + "; "); } else if (param instanceof Boolean) { sb.append(parameterNames[i] + ":" + param + "; "); } else if (param instanceof Date) { sb.append(parameterNames[i] + ":" + param + "; "); } else { sb.append(parameterNames[i] + ":" + getString(param) + "; "); } } } } sb = sb == null ? new StringBuilder() : sb; //ip地址 HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest(); String ipAddr = IpUtil.getIpAddr(request); //userId String userId = request.getHeader("userId"); //请求路径 String requestURI = request.getRequestURI(); //get还是post方式 String method1 = request.getMethod(); LogExeManager.getInstance().executeLogTask(LogTaskFactory.operationLog(userId,requestURI,method1,(short)1,remark,ipAddr,"操作日志",sb.toString())); Object proceed = joinPoint.proceed(); return proceed; } catch (Exception ex) { LOGGER.error("保存系统日志失败"+ex.getMessage()); return null; } } public static String getString(Object o) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); StringBuffer sb = new StringBuffer(); sb.append("entity["); Field[] farr = o.getClass().getDeclaredFields(); for (Field field : farr) { try { field.setAccessible(true); if (!StringUtils.isEmpty(field.get(o).toString())) { sb.append(field.getName()); sb.append("="); if (field.get(o) instanceof Date) { // 日期的处理 sb.append(sdf.format(field.get(o))); } else { sb.append(field.get(o)); } sb.append("|"); } } catch (Exception e) { e.printStackTrace(); } } sb.append("]"); return sb.toString(); } }
3.该注解放在controller上用于记录操作
package com.towery.util; import java.lang.annotation.*; /** * 操作日志注解 记录操作的模块和描述 * */ @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface AuthLog { String MODULE() default "请求模块"; String REMARK() default "操作日志"; }
4.在controller上使用该注解,则前台请求时会记录操作信息
/** * 修改和新增 * @auther caowei * */ @AuthLog(MODULE ="DeviceController",REMARK="新增或修改设备") @PostMapping("save") public HttpResult save(HttpServletRequest request,@RequestBody DeviceVo deviceVo){ String userId = request.getHeader("userId"); Integer currentUserId = null;// 当前登录用户 if (StringUtils.isNotBlank(userId)) { currentUserId = Integer.valueOf(userId); } return HttpResult.ok(deviceService.save(deviceVo,currentUserId)); }
5.效果展示