aop 打印请求信息

项目中使用 AOP 打印请求信息,打印响应信息。
package com.example.aspect;

import com.alibaba.fastjson.JSON;
import com.google.gson.Gson;
import com.example.util.DateUtil;
import org.apache.commons.lang.ArrayUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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 javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;


/**
* @author mingtian
* @desctiption:类功能说明: aop 切面 打印日志
* @data 2019/12/22
* @version:V1
*/
@Aspect
@Component
public class HttpAspect {

protected Logger logger = LoggerFactory.getLogger(HttpAspect.class);

private Gson gson = new Gson();

/**
* 要处理的方法,包名+类名+方法名
*/
@Pointcut("execution(* com.example.web.controller..*.*(..))")
public void cut() {
}


/**
* 前置通知方法
*
* @param joinPoint
*/
@Before("cut()")
public void doBefore(JoinPoint joinPoint) {
//用于获取类方法
logger.info("------------------------ doBefore ----------------------------");
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
// 记录下请求内容
StringBuffer requestInfo = new StringBuffer();
requestInfo.append("Address: " + request.getRequestURL().toString() + " ");
requestInfo.append("IP: " + request.getRemoteAddr() + " ");
requestInfo.append("MethodName:" + joinPoint.getSignature() + " ");
Object[] args = joinPoint.getArgs();
//序列化时过滤掉request和response
List<Object> logArgs = streamOf(args).filter(arg -> (!(arg instanceof HttpServletRequest) && !(arg instanceof HttpServletResponse)))
.collect(Collectors.toList());
String argStr = JSON.toJSONString(logArgs);
requestInfo.append("RequestParam:" + argStr + " ");
logger.info(DateUtil.getNowDate() + ",RequestInfo: " + requestInfo);
}

/**
* 过滤工具类
*
* @param array
* @param <T>
* @return
*/
public static <T> Stream<T> streamOf(T[] array) {
return ArrayUtils.isEmpty(array) ? Stream.empty() : Arrays.asList(array).stream();
}

/**
* 后置通知
*/
@After("cut()")
public void doAfter() {
logger.info("-------------------------------doAfter-----------------------");
}

/**
* 执行完方法之后返回的参数
*
* @param obj
*/
@AfterReturning(returning = "obj", pointcut = "cut()")
public void doAfterReturning(Object obj) {
// 处理完请求,返回相应参数
logger.info(DateUtil.getNowDate() + ",ResponseResult:" + gson.toJson(obj));
}
}
注意:
DateUtil.getNowDate()  是一个获取当前时间的工具类,如下。
/**
* 格式化日期 格式:yyyy-MM-dd HH:mm:ss SSS
*/
public static String getNowDate() {
String format = "yyyy-MM-dd HH:mm:ss SSS";
return LocalDateTime.now().format(DateTimeFormatter.ofPattern(format));
}
原文地址:https://www.cnblogs.com/ming-blogs/p/12079689.html