自定义注解实现记录请求日志
- 创建注解
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface SysLog {
String value() default "";
}
-
编写切面类
@Aspect @Component @Slf4j public class RequestLogAspect { @Autowired private RequestLogMapper requestLogMapper; /** * 声明一个切点 */ @Pointcut(value = "@annotation(com.sangfor.csw.aop.SysLog)") public void logPointCut() { } /** * 环绕通知 * @param joinPoint * @return * @throws Throwable */ @Around("logPointCut()") public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable { Object result ;//= null; //前置参数保存 RequestLog requestLog = new RequestLog(); requestLog.setStartTime(LocalDateTime.now()); Map<String, String> nameAndValue = getNameAndValue(joinPoint); requestLog.setParam(JSON.toJSONString(nameAndValue)); requestLog.setStatus(0); requestLog.setMethodName(joinPoint.getSignature().getName()); requestLogMapper.insert(requestLog); long time = System.currentTimeMillis(); //执行切点 try { result = joinPoint.proceed(); } catch (Exception e) { requestLog.setErrorMsg(e.getMessage()); requestLogMapper.updateById(requestLog); throw new RuntimeException(e); } //after time = System.currentTimeMillis() - time; requestLog.setFinishTime(time); requestLog.setStatus(1); requestLogMapper.updateById(requestLog); return result; } /** * 获取参数Map集合 * @param joinPoint * @return */ Map<String, String> getNameAndValue(ProceedingJoinPoint joinPoint) { Map<String, String> param = new HashMap<>(); Object[] paramValues = joinPoint.getArgs(); String[] paramNames = ((CodeSignature)joinPoint.getSignature()).getParameterNames(); for (int i = 0; i < paramNames.length; i++) { param.put(paramNames[i],JSON.toJSONString(paramValues[i])); } return param; } }
-
数据库对应的实体类
@Data @TableName("request_log") public class RequestLog { /** * 唯一id */ @TableId(value = "id", type = IdType.AUTO) private Long id; /** * 请求方法名 */ private String methodName; /** * 请求方式 */ private String type; /** * 请求参数 */ private String param; /** * 开始时间 */ private LocalDateTime startTime; /** * 请求耗时 */ private Long finishTime; /** * 接口返回时间 */ private LocalDateTime returnTime; /** * 接口返回值 */ private String returnData; /** * 请求状态 1成功,0失败 */ private Integer status; /** * 错误信息 */ private String errorMsg; }
-
使用
@SysLog @PostMapping("/save") public R saveUser(@RequestBody User user) { String msg = userService.saveUser(user); return R.success(msg); }
- 参考资料