在程序中日志是很重要的一部分信息,我们需要记录的业务日志十分多,因此为了方便日志处理,我们利用AOP的原理进行日志处理。
拿controller的接口为例,我们定义切面为controller层的所有类,
利用前置增强方法,获取controller层每个请求的请求对象信息;进行日志打印
利用后置增强方法;获取controller层每个请求的返回对象信息;进行日志打印。
代码如下
package com.hyl.springboot.aop;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hyl.springboot.zUtils.utils.JsonUtil;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
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.text.SimpleDateFormat;
import java.util.Enumeration;
import java.util.List;
import java.util.UUID;
@Aspect
@Component
/*@Slf4j*/
//打印请求的结果日志信息
public class WebLogAspect {
private static Logger log = LoggerFactory.getLogger(JsonUtil.class);
//定义切面
// @Pointcut("execution(public * com.aiyijia.springbootdemo.controller..*.*(..))")
@Pointcut("@annotation(org.springframework.web.bind.annotation.RequestMapping) || @annotation(org.springframework.web.bind.annotation.GetMapping) || @annotation(org.springframework.web.bind.annotation.PostMapping)")
public void webLog() {
}
@Before("webLog()")
public void doBefore(JoinPoint joinPoint) throws Throwable {
// 接收到请求,记录请求内容
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
MDC.clear();
MDC.put("uuid", UUID.randomUUID().toString().replace("-", ""));
log.info("#####请求开始####################################");
// 记录下请求内容
log.info("URL : " + request.getRequestURL().toString());
log.info("HTTP_METHOD : " + request.getMethod());
// log.info("IP : " + request.getRemoteAddr());
log.info("CLASS_METHOD : " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
Enumeration<String> enu = request.getParameterNames();
while (enu.hasMoreElements()) {
String name = (String) enu.nextElement();
log.info("name:{" + name + "},value:{" + request.getParameter(name) + "}");
}
}
@AfterReturning(returning = "ret", pointcut = "webLog()")
public void doAfterReturning(JoinPoint joinPoint, Object ret) throws Throwable {
// 处理完请求,返回内容
if (log.isInfoEnabled()) {
log.info("RESPONSE : " + ret);
log.info("###################################请求结束######");
}
ObjectMapper mapper = new ObjectMapper();
mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
try {
if (log.isDebugEnabled()) {
log.debug("returnValue={}", mapper.writeValueAsString(ret));
}
} catch (Exception exc) {
log.error("拦截器异常", exc);
}
}
}