美团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();
}
}
}