上一篇说了一下《解决问题的一般套路》,里面讲到了日志系统的重要性,日志重要吗?监控重要吗?of course!日志就是要能找到用户做了什么请求那个机器。
上下游接口请求,请求参数和入参是否正确,我们可以统一写一个面向切面方法去打印日志,不用每一处去写,切入点大家自己按照规则定义,AOP是Spring提供的关键特性之一。AOP即面向切面编程,是OOP编程的有效补充。使用AOP技术,可以将一些系统性相关的编程工作,独立提取出来,独立实现,然后通过切面切入进系统。从而避免了在业务逻辑的代码中混入很多的系统相关的逻辑——比如权限管理,事物管理,日志记录等等。这些系统性的编程工作都可以独立编码实现,然后通过AOP技术切入进系统即可。从而达到了 将不同的关注点分离出来的效果。
@Aspect @Component public class ControllerLogAspect { private Logger logger = LoggerFactory.getLogger(getClass()); ThreadLocal<Long> startTime = new ThreadLocal<>(); @Pointcut("execution(* com.xxx.mobile.web.controller..*.*(..))") public void controllerLog() { } @Before("controllerLog()") public void doBefore(JoinPoint joinPoint) throws Throwable { startTime.set(System.currentTimeMillis()); if (joinPoint == null) { return; } Signature signature = joinPoint.getSignature(); // 接收到请求,记录请求内容 RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes(); ServletRequestAttributes attributes = null; HttpServletRequest request = null; String requestUrl = ""; String httpMethod = ""; String declaringTypeName = ""; String actionName = ""; String ip = ""; if (requestAttributes != null) { attributes = (ServletRequestAttributes) requestAttributes; } if (attributes != null) { request = attributes.getRequest(); } if (request != null) { requestUrl = request.getRequestURL().toString(); httpMethod = request.getMethod(); ip = IpUtils.getIpAddr(request); } if (signature != null) { declaringTypeName = joinPoint.getSignature().getDeclaringTypeName(); actionName = joinPoint.getSignature().getName(); } // 记录下请求内容 logger.debug("URL:[{}] HTTP_METHOD:[{}] CLASS_METHOD:[{}.{}] ip:[{}] ARGS:{}", requestUrl, httpMethod, declaringTypeName, actionName, ip, Arrays.toString(joinPoint.getArgs())); } @AfterReturning(returning = "ret", pointcut = "controllerLog()") public void doAfterReturning(Object ret) throws Throwable { // 处理完请求,返回内容 logger.debug("Execute Time:{}ms \n{}", (System.currentTimeMillis() - startTime.get()), ret); }
下面将使用@ExceptionHandler
处理全局异常,将异常信息更加人性化的输出给用户。当然我们记录日志还是会用log4j。至于log4j的用法大家可以百度。
@ControllerAdvice public class MobileWebExceptionHandler { private static Logger logger = LoggerFactory.getLogger(MobileWebExceptionHandler.class); @ExceptionHandler(value = Exception.class) @ResponseBody public Object exceptionHandler(HttpServletRequest request, Exception e) throws Exception { String message = String.format("Url:[%s]-%s", request.getRequestURL().toString(), e.getMessage()); logger.error(message, e); return MobileWebResponse.error(CODE_INVALID_PARAMETER, e.getMessage()); }
通过@ControllerAdvice
。我们可以将对于控制器的全局配置放置在同一个位置,注解了@ControllerAdvice
的类的方法可以使用@ExceptionHandler
,@InitBinder
,@ModelAttribute
注解到方法上,这对所有注解了@RequestMapping
的控制器内的方法有:
@ExceptionHandler
:用于全局处理控制器里面的异常。@InitBinder
:用来设置WebDataBinder
,WebDataBinder
用来自动绑定前台请求参数到Model
中。@ModelAttribute
:@ModelAttribute
本来的作用是绑定键值对到Model
里