美团Cat - CatFilter

美团Cat之CatFilter

Cat的TraceContext是在什么时候被清除呢?

具体实现类:com.dianping.cat.servlet.CatFilter

package com.dianping.cat.servlet;

@WebFilter(urlPatterns = "/*", filterName = "cat-filter", dispatcherTypes = {DispatcherType.REQUEST, DispatcherType.FORWARD}, asyncSupported = true)
public class CatFilter implements Filter {
    private List<Handler> m_handlers = new ArrayList<Handler>();

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
            ServletException {
        if (needFilter(request)) {
            Context ctx = new Context((HttpServletRequest) request, new StatusExposingServletResponse((HttpServletResponse) response), chain, m_handlers);
            ctx.handle();
        } else {
            chain.doFilter(request, response);
        }
    }

    @Override
    public void destroy() {}

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        m_handlers.add(CatHandler.ENVIRONMENT);
        m_handlers.add(CatHandler.ID_SETUP);
        m_handlers.add(CatHandler.LOG_SPAN);
        m_handlers.add(CatHandler.LOG_CLIENT_PAYLOAD);
    }


    protected static class Context {
        public void handle() throws IOException, ServletException {
            if (m_index < m_handlers.size()) {
                Handler handler = m_handlers.get(m_index++);'
                //递归
                handler.handle(this);
            } else {
                m_chain.doFilter(m_request, m_response);
            }
        }
    
    }

    protected interface Handler {
        public void handle(Context ctx) throws IOException, ServletException;
    }

    enum CatHandler implements Handler {
        ENVIRONMENT {},
        ID_SETUP {},
        LOG_CLIENT_PAYLOAD {},
        LOG_SPAN {}
    }

}

CatHanlder

LOG_SPAN

 LOG_SPAN {
         @Override
         public void handle(Context ctx) throws IOException, ServletException {
            HttpServletRequest req = ctx.getRequest();

            Transaction t = Cat.newTransaction(ctx.getType(), getRequestURI(req));

            try {
               fillMdc(ctx);
               restoreTraceContext(req);
               FilterHelper.checkUcsContext();
               ctx.handle();
               customizeStatus(t, req);
            } finally {
               if (Cat.getTraceContext(false) != null) {
                  Cat.logEvent("URL.Trace.Context", "Context", Message.SUCCESS, Cat.getTraceContext(false).toString());
                  Cat.removeTraceContext();
               }
               t.complete();
            }
        }
      }
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容