最近公司要做系统优化,但是项目并没有数据分析埋点,接口响应时间没有做记录,只能从线上出现的问题来做具体的分析。
由此提出通过记录日志的形式做接口响应时长,首先就是想到的使用filter,我们公司框架使用的zk+dubbo,正好使用到了dubbo的filter能够精确到具体方法上
我们做法 使用拦截器记录接口的响应时间、创建日志id 方便后期日志查询 使用filter记录提供方服务响应时间
代码:
Interceptor
@Component
@Slf4j
public class InterceptorByDubbo implements HandlerInterceptor {
public static ThreadLocal threadLocal = new ThreadLocal();
Long start;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
start = System.currentTimeMillis();
//创建日志id
threadLocal.set(UUID.randomUUID().toString());
return true;
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
//清除变量 防止oom
threadLocal.remove();
// 记录接口相应时长
log.info("接口[ {} ] 耗时 [ {} ]",request.getRequestURI(),System.currentTimeMillis() - start);
}
}
filter
//order 排名 越小越靠前
//greop 触发的时机
@Slf4j
//@Activate(group = {CommonConstants.CONSUMER,Constants.TOKEN_KEY},order = 10000)
@Activate(group = {CommonConstants.CONSUMER,CommonConstants.PROVIDER},order = 10000)
public class TestDubboFilter implements Filter {
@Override
public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
Result result ;
long start = System.currentTimeMillis();
if (RpcContext.getContext().isConsumerSide()){
result = invoker.invoke(invocation);
log.info("dubbo Filter Log consumer log 打印 耗时[ {} ] LogId [ {} ] 方法名称[ {} ]",System.currentTimeMillis() -start, InterceptorByDubbo.threadLocal.get(),invocation.getMethodName());
}else if (RpcContext.getContext().isProviderSide()){
result = invoker.invoke(invocation);
log.info("dubbo Filter Log provider log 打印 耗时[ {} ] LogId [ {} ] 方法名称[ {} ]",System.currentTimeMillis() -start, InterceptorByDubbo.threadLocal.get(),invocation.getMethodName());
}else {
log.info("日志打印了");
result = invoker.invoke(invocation);
}
return result;
}
}
创建dubo配置
这是自己着手做的一个小demo,大致的思路就是这样,可能具体细节还需要在优化,具体问题具体分析
自主学习 有不对的地方大神帮忙指点一下