AOP日志
通过AOP切面来实现日志,打印出用户请求的URL,携带的参数,用户的ID及姓名,响应结果,耗时等信息,这样我们就可以根据用户来进行排查错误
@Aspect
@Component
@Slf4j
@EnableAspectJAutoProxy
public class RequestAspect {
//切点为controller层
@Pointcut("execution(public * com.djn.web.controller.*.*(..)))")
public void requestCutPoint() {
}
@Around("requestCutPoint()")
public Object doAround(ProceedingJoinPoint call) throws Throwable {
ServletRequestAttributes servletRequestAttributes =
(ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = servletRequestAttributes.getRequest();
//请求url
// 记录下请求内容
//用户的信息,我这里用的Shiro
User user = (User) SecurityUtils.getSubject().getSession().getAttribute(Const.CURRENT_USER);
if (user == null) {
user = new User(0, "未登录", "", 0);
}
log.info("################ api日志开始 ################");
log.info("请求用户 id={}, phone={} : ", user.getUserId(), user.getUsername());
log.info("请求URL : " + request.getRequestURL().toString());
log.info("请求HTTP_METHOD : " + request.getMethod());
//请求参数
Object[] args = call.getArgs();
if (args != null) {
StringBuilder sb = new StringBuilder("userId=" + user.getUserId() + "|");
for (Object arg : args) {
if (arg instanceof HttpServletRequest) {
continue;
} else if (arg instanceof HttpServletResponse) {
continue;
}
sb.append(arg);
sb.append("|");
}
log.info("请求参数: " + sb);
}
Long startTimeStamp = System.currentTimeMillis();
try {
// 请求处理
Object object = call.proceed();
log.info("【响应结果】: " + (null != object ? JSONObject.toJSONString(object) : null));
return object;
} catch (Exception e) {
log.error("服务请求处理异常", e);
return ServerResponse.createByError("服务请求处理异常");
} finally {
log.info("################ api日志结束 耗时: {}毫秒 ################", (System.currentTimeMillis() - startTimeStamp));
}
}
}

浙公网安备 33010602011771号