springboot全局异常捕获和AOP统一处理web请求日志

1、项目中会使用异常捕获,然而每个controller方法都加上try catch会显得很冗余,这时候就需要全局捕获异常,所有的异常都到我自定义的异常捕获中去。
在springboot中使用@ControllerAdvice注解实现全局异常捕获,代码如下:

@ControllerAdvice(basePackage="com.cjs.example.controller")
public class GlobalExceptionHandler {
	private Logger logger = LoggerFactory.getLogger(getClass());

	@ExceptionHandler(RuntimeException.class)
	@ReponseBody
	public Map errorMsg(HttpServletRequest request){
		logger.error("错误链接"+request.getRequestURL().toString());
		ex.printStackTrace();
		Map errorMsgResult=new HashMap<>();
		errorMsgResult.put("code", 500);
		errorMsgResult.put("msg", "抛出异常");
		return errorMsgResult;
	}
}

并在pom中导入log4j的配置


	org.springframework.boot
	spring-boot-starter-log4j

2、对于所有web请求来说,想要对web请求的日志进行记录,在请求前和请求后记录日志。这时候就需要AOP来记录日志。
springboot中支持aop,配置如下:


	org.springframework.boot
	spring-boot-starter-aop

具体的切面编程如下:

@Aspect
@Component
public class WebLogAspect {
	private Logger logger = LoggerFactory.getLogger(getClass());

	@Pointcut("excution(public * com.cjs.example.controller.*.*(..))")
	private void weblog(){}

	@Before("weblog()")
	private coid doBefore(JoinPoint joinPoint) throws Throwable {
		ServletRequestAttributes attributes = (ServletRequestAttributes)RequetsContextHolder.getRequestAttributes();
		HttpServletRequest request = attributes.getRequest();
		logger.info("URL: "+request.getRequestURL().toString());
		logger.info("HTTP_METHOD: "+request.getMethod());
		logger.info("IP: "+request.getRemoteAddr());
		Enumeration enu = request.getParameterNames();
		while (enu.hasMpreElements()) {
			String name = enu.nextElement();
			logger.info("name:{},value:{}", name, request.getParameter(name));
		}
	}

	@AfterReturning(returning = "ret", pointcut = "weblog()")
	public void doAfterReturning(Object ret) throws Throwable {
		logger.info("RESPONSE: " + ret);
	}
}

你可能感兴趣的:(网页前端后端)