日志拦截打印返回的数据格式

/**
 * 打印请求后返回的数据格式
 *
 */
@Aspect
@Component
@Slf4j
public class LogAop {

  @Autowired
  private ObjectMapper objectMapper;
  
  private static final String LOG = "ip: {}  ,url:{}  ,params: {}, responseBody: {}";

  @Around("execution(* controller包路劲..*(..))")
  public Object printLog(ProceedingJoinPoint point) throws Throwable {
    Object result = null;
    // 接收到请求,记录请求内容
    ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
    if(attributes!=null) {
      result =point.proceed();
      if(result!=null) {
        HttpServletRequest request= attributes.getRequest();
        log.info(LOG, IPUtils.getIpAddr(request), request.getRequestURI(), HttpUtils.getParameterStringMap(request),objectMapper.writeValueAsString(result));
       
      }
    }
    return result; 
  }
}



public class HttpUtils {
  
  public static Map<String, String> getParameterStringMap(HttpServletRequest request) {
    Map<String, String[]> properties = request.getParameterMap();// 把请求参数封装到Map<String, String[]>中
    Map<String, String> returnMap = new TreeMap<String, String>();
    String name = "";
    String value = "";
    for (Map.Entry<String, String[]> entry : properties.entrySet()) {
      name = entry.getKey();
      if (!"files".startsWith(name)) {
        String[] values = entry.getValue();
        if (null == values) {
          value = "";
        } else if (values.length > 1) {
          for (int i = 0; i < values.length; i++) { // 用于请求参数中有多个相同名称
            value = values[i] + ",";
          }
          value = value.substring(0, value.length() - 1);
        }else if (value.length()==0){
           value="";
        }
        else {
          value = values[0];// 用于请求参数中请求参数名唯一
        }
        returnMap.put(name, value);

      }
    }

    return returnMap;
  }

}

 

展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 技术黑板 设计师: CSDN官方博客
应支付0元
点击重新获取
扫码支付

支付成功即可阅读