①自定义一个过滤器 DubboLoggerFilter.java
import org.apache.dubbo.rpc.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.fastjson.JSON;
/**
* @Author: JCccc
* @Description: dubbo请求和响应拦截(记录请求参数和响应结果和时长)
* @Date: Create in 19:03 2021/1/26
*/
public class DubboLoggerFilter implements Filter {
protected Logger logger = LoggerFactory.getLogger(getClass());
/**
* rpc日志最长字符串
*/
private final static Integer MAX_LOG_LENGTH=5000;
/**
* rpc日志超过长度截取长度
*/
private final static Integer REMAINING_LOG_LENGTH=1000;
@Override
public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
String methodName = invocation.getMethodName();
Object[] arguments = invocation.getArguments();
String className = invoker.getInterface().getName();
String callMethod = className + "." + methodName;
String argsJson = JSON.toJSONString(arguments);
logger.info("rpc接口callMethod:{}>>入参:{}", callMethod, argsJson);
long start = System.currentTimeMillis();
AsyncRpcResult result = (AsyncRpcResult)invoker.invoke(invocation);
if(result.hasException()){
logger.info("rpc接口callMethod:{},接口耗时:{},异常:{},", callMethod, System.currentTimeMillis() - start,result.getException().getMessage());
} else {
Object resultString = JSON.toJSON(result.getAppResponse().getValue());
if(resultString!=null&&resultString.toString().length()>MAX_LOG_LENGTH){
resultString=resultString.toString().substring(0,REMAINING_LOG_LENGTH)+"...";
}
logger.info("rpc接口callMethod:{},出参:{},接口耗时:{}", callMethod,resultString , System.currentTimeMillis() - start);
}
return result;
}
}
② 加上配置