springcloudzuulfilter实现get,post请求⽇志记录功能import com.alibaba.fastjson.JSONObject;
import com.idoipo.infras.del.InvokeLogModel;
import com.idoipo.infras.gateway.open.service.IInvokeLogService;
import com.idoipo.infras.gateway.open.utils.MultiPartFormDateToJson;
import comflix.zuul.ZuulFilter;
import t.RequestContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloudflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;
import org.springframework.util.StreamUtils;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.Date;
import java.util.Map;
/**
* Create by liping on 2018/9/11
* 接⼝调⽤⽇志记录过滤器
*/
@Component
public class LogRecodePostFilter extends ZuulFilter {
private static final Logger logger = Logger(LogRecodePostFilter.class);
@Autowired
IInvokeLogService invokeLogService;
@Override
public String filterType() {
return FilterConstants.POST_TYPE;//要打印返回信息,必须得⽤"post"
}
@Override
public int filterOrder() {
return FilterConstants.PRE_DECORATION_FILTER_ORDER + 2;
}
@Override
public boolean shouldFilter() {
RequestContext context = CurrentContext();
Boolean isSuccess = (boolean) ("isSuccess");
return isSuccess;
}
@Override
public Object run() {
try {
logger.info("进⼊⽇志记录过滤器");
RequestContext ctx = CurrentContext();
HttpServletRequest request = Request();
InputStream in = InputStream();
String method = Method();
String interfaceMethod = ServletPath();
//logger.info("请求⽅法method={},url={}",method,interfaceMethod);
String reqBody = pyToString(in, Charset.forName("UTF-8"));
int user = 0;
String invokeUser = "";
if ("GET".UpperCase())) {
Map<String, String[]> map = ParameterMap();
// 打印请求url参数
if (map != null) {
StringBuilder sb = new StringBuilder();
sb.append("{");
for (Map.Entry<String, String[]> entry : Set()) {
String key = Key();
String value = Value());
sb.append("[" + key + "=" + value + "]");
if ("user".equals(key)) {
invokeUser = value;
} else if ("userFlag".equals(key)) {
user = Integer.parseInt(value);
}
}
sb.append("}");
reqBody = sb.toString();
//logger.info("reqBody ={}" + reqBody);
}
} else if ("POST".UpperCase())) {
//打印请求json参数
if (reqBody != null) {
String conType = Header("content-type");
//post请求⽬前获取userFlag,user参数只⽀持multipart/form-data,application/json,对于其他⽅式不记录⽤户信息
if (ains("multipart/form-data") || ains("application/json")) {
if (ains("multipart/form-data")) {
reqBody = MultiPartFormDateToJson.formDateToJson(reqBody);
}
//默认content-type传json-->application/json
Object userObject;
Object invokeUserObject;
JSONObject jsonObject = JSONObject.parseObject(reqBody);
userObject = ("userFlag");
if (null != userObject) {
user = Integer.String());
} else {
logger.warn("当前请求缺少userFlag");
}
invokeUserObject = ("user");
if (null != userObject) {
invokeUser = String();
} else {
logger.warn("当前请求缺少user");
}
/
/logger.info("reqBody:={}" + reqBody);
}
}
}
// 打印response
InputStream out = ResponseDataStream();
String outBody = pyToString(out, Charset.forName("UTF-8"));
boolean result = false;
if (outBody != null && "" != outBody) {
JSONObject jsonObject = JSONObject.parseObject(outBody);
Object dataFlagObject = ("dataFlag");
if (null != dataFlagObject) {
int flag = Integer.String());
if (flag == 1) {
result = true;
}
}
//logger.info("响应参数:={}" + outBody);
}
//必须重新写⼊流//重要
ctx.setResponseBody(outBody);
InvokeLogModel logModel = new InvokeLogModel();
logModel.setUid(user);
logModel.setInvokeUser(invokeUser);
logModel.setInterfaceName(interfaceMethod);
logModel.setInterfaceMethod(method);
logModel.setInvokeStartTime(new Date());
logModel.setInvokeEndTime(null);
logModel.setRequestParam(reqBody);
logModel.setResponseResult(result);
logModel.setResponseBody(outBody);
invokeLogService.insertInvokerLog(logModel);
} catch (IOException e) {
<("LogRecode IO异常", e);
}
return null;
}
String printArray(String[] arr) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < arr.length; i++) {
sb.append(arr[i]);
if (i < arr.length - 1) {
sb.append(",");
}
}
String();
}
}
当是post请求的格式不是application/json格式,⽽是multipart/form-data格式时,数据不能直接转json对象,需要进⾏匹配,可以使⽤如下⼯具类
import com.alibaba.fastjson.JSON;
import org.apachemons.lang.StringUtils;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
/**
* 当数据
* Create by liping on 2018/9/14
*/
public class MultiPartFormDateToJson {
public static Map<String, String> toMap(String params) {
Map<String, String> map = new HashMap<>();
//获得分隔符
String boundary = params.split("\r\n")[0];
//获得分割后的参数
String[] ps = Optional.ofNullable(params).orElse("").split(boundary);
for (String p : ps) {
if(p.equals(""))
continue;
if (p.equals("--\r\n"))
continue;
p = p.trim().replaceAll("\r\n", "&&");
String[] ds = p.split(";");
//获得参数名
String nameMeta = Arrays.asList(ds).stream()
.filter(d -> d.trim().startsWith("name="))
.findAny()
.
orElse("");
String name = Optional.ofNullable(nameMeta.split("\"")[1]).orElse("");
//获得参数值
String value = Optional.ofNullable(StringUtils.substringAfter(p,"&&&&")).orElse("");
map.put(name, value);
}
return map;
}
public static String formDateToJson(String param){
spring framework网络系统参数return  JSONString(toMap(param));
}
}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。