美團Cat - CatFilter

美團Cat之CatFilter

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

具體實現(xiàn)類: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();
            }
        }
      }
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容