摘要: 原创出处 http://www.iocoder.cn/SkyWalking/agent-plugin-tomcat/ 「芋道源码」欢迎转载,保留摘要,谢谢!
本文主要基于 SkyWalking 3.2.6 正式版
1. 概述
本文主要分享 SkyWalking Agent Tomcat 插件。涉及到的代码不多,如下图:
2. TomcatInstrumentation
在 skywalking-plugin.def
里,定义了插件,如下图:
org.skywalking.apm.plugin.tomcat78x.define.TomcatInstrumentation
,实现 ClassInstanceMethodsEnhancePluginDefine 抽象类,定义了方法切面,代码如下:
2.1 TomcatInvokeInterceptor
org.skywalking.apm.plugin.tomcat78x.TomcatInvokeInterceptor
,实现 InstanceMethodsAroundInterceptor 接口,TomcatInstrumentation 的拦截器。代码如下:
#beforeMethod(...)
方法,创建 EntrySpan 对象。代码如下:- 第 59 至 65 行:解析 ContextCarrier 对象,用于跨进程的链路追踪。在 《SkyWalking 源码分析 —— Agent 收集 Trace 数据》「 3.2.3 ContextCarrier 」 有详细解析。
- 第 68 行:调用
ContextManager#createEntrySpan(operationName, contextCarrier)
方法,创建 EntrySpan 对象。 - 第 71 至 72 行:设置 EntrySpan 对象的
url
/http.method
标签键值对。 - 第 75 行:设置 EntrySpan 对象的组件类型。
- 第 78 行:设置 EntrySpan 对象的分层。
#afterMethod(...)
方法,完成 EntrySpan 对象。- 第 89 至 92 行:当返回状态码大于等于 400 时,标记 EntrySpan 发生异常,并设置
status_code
标签键值对。 - 第 95 行:调用
ContextManager#stopSpan()
方法,完成 EntrySpan 对象。
- 第 89 至 92 行:当返回状态码大于等于 400 时,标记 EntrySpan 发生异常,并设置
#handleMethodException(...)
方法,处理异常。注意,该方法实际并且调用,在 Tomcat 的StandardWrapperValve#invoke(request, response)
方法里,发生异常时,会提交异常给StandardWrapperValve#exception(request, response, exception)
处理,所以会被 「 2.2 TomcatExceptionInterceptor 」 拦截。
2.2 TomcatExceptionInterceptor
org.skywalking.apm.plugin.tomcat78x.TomcatExceptionInterceptor
,实现 InstanceMethodsAroundInterceptor 接口,TomcatInstrumentation 的拦截器。代码如下:
#beforeMethod(...)
方法,处理异常。代码如下:- 第 35 行:调用
AbstractSpan#errorOccurred()
方法,标记 EntrySpan 对象发生异常。 - 第 35 行:调用
AbstractSpan#log(Throwable)
方法,记录异常日志到 EntrySpan 对象。
- 第 35 行:调用
