|
| 1 | +import * as api from '@opentelemetry/api'; |
| 2 | +import * as core from '@opentelemetry/core'; |
| 3 | +import { InstrumentationBase, isWrapped } from '@opentelemetry/instrumentation'; |
| 4 | +import * as web from '@opentelemetry/sdk-trace-web'; |
| 5 | +import { |
| 6 | + SEMATTRS_HTTP_HOST, |
| 7 | + SEMATTRS_HTTP_METHOD, |
| 8 | + SEMATTRS_HTTP_SCHEME, |
| 9 | + SEMATTRS_HTTP_STATUS_CODE, |
| 10 | + SEMATTRS_HTTP_URL, |
| 11 | + SEMATTRS_HTTP_USER_AGENT, |
| 12 | +} from '@opentelemetry/semantic-conventions'; |
| 13 | +import { Axios, AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios'; |
| 14 | + |
| 15 | +import { AttributeNames } from './constants'; |
| 16 | +import type { AxiosInstrumentationOptions } from './types'; |
| 17 | + |
| 18 | +/** |
| 19 | + * Additional custom attribute names |
| 20 | + */ |
| 21 | + |
| 22 | +export const VERSION = '1.12.3'; |
| 23 | + |
| 24 | +/** |
| 25 | + * Configuration interface for the AxiosInstrumentation |
| 26 | + */ |
| 27 | + |
| 28 | +export class AxiosInstrumentation extends InstrumentationBase<AxiosInstrumentationOptions> { |
| 29 | + readonly component: string = 'axios'; |
| 30 | + |
| 31 | + readonly version: string = VERSION; |
| 32 | + |
| 33 | + moduleName = this.component; |
| 34 | + |
| 35 | + constructor(config: AxiosInstrumentationOptions = {}) { |
| 36 | + super('@grafana/instrumentation-axios', VERSION, config); |
| 37 | + this.enable = this.enable.bind(this); |
| 38 | + this.disable = this.disable.bind(this); |
| 39 | + } |
| 40 | + |
| 41 | + init(): void { |
| 42 | + // no-op |
| 43 | + } |
| 44 | + |
| 45 | + private _addFinalSpanAttributes(span: api.Span, response: AxiosResponse) { |
| 46 | + const responseUrl = `${response.config.baseURL ?? ''}/${response.config.url}`; |
| 47 | + const parsedUrl = web.parseUrl(responseUrl); |
| 48 | + |
| 49 | + span.updateName(`${response.config.method?.toUpperCase()}`); |
| 50 | + span.setAttribute(SEMATTRS_HTTP_STATUS_CODE, response.status); |
| 51 | + if (response.statusText != null) { |
| 52 | + span.setAttribute(AttributeNames.HTTP_STATUS_TEXT, response.statusText); |
| 53 | + } |
| 54 | + span.setAttribute(SEMATTRS_HTTP_HOST, parsedUrl.host); |
| 55 | + span.setAttribute(SEMATTRS_HTTP_SCHEME, parsedUrl.protocol.replace(':', '')); |
| 56 | + if (typeof navigator !== 'undefined') { |
| 57 | + span.setAttribute(SEMATTRS_HTTP_USER_AGENT, navigator.userAgent); |
| 58 | + } |
| 59 | + |
| 60 | + try { |
| 61 | + this._config.applyCustomAttributesOnSpan?.(span as web.Span, response); |
| 62 | + } catch (e) { |
| 63 | + this._diag.error('Error applying custom attributes', e); |
| 64 | + } |
| 65 | + } |
| 66 | + |
| 67 | + private _addAxiosHeaders(config: AxiosRequestConfig): void { |
| 68 | + const headers: Record<string, unknown> = config.headers || {}; |
| 69 | + api.propagation.inject(api.context.active(), headers); |
| 70 | + // @ts-ignore |
| 71 | + config.headers = headers; |
| 72 | + } |
| 73 | + |
| 74 | + private createSpan(url: string, options: Partial<Request | RequestInit> = {}): api.Span | undefined { |
| 75 | + if (core.isUrlIgnored(url, this.getConfig().ignoreUrls)) { |
| 76 | + this._diag.debug('ignoring span as url matches ignored url'); |
| 77 | + return; |
| 78 | + } |
| 79 | + |
| 80 | + const method = (options.method || 'GET').toUpperCase(); |
| 81 | + const spanName = `HTTP ${method}`; |
| 82 | + |
| 83 | + return this.tracer.startSpan(spanName, { |
| 84 | + kind: api.SpanKind.CLIENT, |
| 85 | + attributes: { |
| 86 | + [AttributeNames.COMPONENT]: this.moduleName, |
| 87 | + [SEMATTRS_HTTP_METHOD]: method, |
| 88 | + [SEMATTRS_HTTP_URL]: url, |
| 89 | + }, |
| 90 | + }); |
| 91 | + } |
| 92 | + |
| 93 | + private _endSpan<T = any>(span: api.Span, response?: AxiosResponse<T>, error?: Error) { |
| 94 | + if (response) { |
| 95 | + // It's an AxiosResponse |
| 96 | + this._addFinalSpanAttributes(span, response); |
| 97 | + |
| 98 | + if (response.status >= 400) { |
| 99 | + span.setStatus({ code: api.SpanStatusCode.ERROR }); |
| 100 | + } else { |
| 101 | + span.setStatus({ code: api.SpanStatusCode.OK }); |
| 102 | + } |
| 103 | + } else if (error) { |
| 104 | + // It's an error object |
| 105 | + span.setStatus({ code: api.SpanStatusCode.ERROR, message: error.message }); |
| 106 | + if (error.name) { |
| 107 | + span.setAttribute(AttributeNames.HTTP_ERROR_NAME, error.name); |
| 108 | + } |
| 109 | + } |
| 110 | + |
| 111 | + span.end(); |
| 112 | + } |
| 113 | + |
| 114 | + private _patchAxios() { |
| 115 | + const plugin = this; |
| 116 | + |
| 117 | + // Wrap axios.request |
| 118 | + if (isWrapped(Axios.prototype.request)) { |
| 119 | + plugin._unwrap(Axios.prototype, 'request'); |
| 120 | + } |
| 121 | + |
| 122 | + plugin._wrap( |
| 123 | + Axios.prototype, |
| 124 | + 'request', |
| 125 | + (original: <T = any, R = AxiosResponse<T>, D = any>(config: AxiosRequestConfig<D>) => Promise<R>) => { |
| 126 | + return function patchRequest<T = any, R = AxiosResponse<T>, D = any>( |
| 127 | + this: AxiosInstance, |
| 128 | + requestConfig: AxiosRequestConfig<D> |
| 129 | + ): Promise<R> { |
| 130 | + const url = requestConfig.url ?? ''; |
| 131 | + |
| 132 | + // Create a new span if the URL is not ignored |
| 133 | + const span = plugin.createSpan(url, { method: requestConfig.method }); |
| 134 | + if (!span) { |
| 135 | + return original.apply(this, [requestConfig]) as Promise<R>; |
| 136 | + } |
| 137 | + |
| 138 | + return api.context.with(api.trace.setSpan(api.context.active(), span), () => { |
| 139 | + plugin._addAxiosHeaders(requestConfig); |
| 140 | + |
| 141 | + return (original.apply(this, [requestConfig]) as Promise<R>) |
| 142 | + .then((response: R) => { |
| 143 | + try { |
| 144 | + plugin._endSpan<T>(span, response as AxiosResponse<T>); |
| 145 | + } catch (e) { |
| 146 | + plugin._diag.error('Error ending span', e); |
| 147 | + } |
| 148 | + return response; |
| 149 | + }) |
| 150 | + .catch((error: any) => { |
| 151 | + try { |
| 152 | + plugin._endSpan( |
| 153 | + span, |
| 154 | + error?.response, |
| 155 | + error?.response || { |
| 156 | + message: error?.message || 'Unknown error', |
| 157 | + name: error?.name || 'Error', |
| 158 | + } |
| 159 | + ); |
| 160 | + } catch (e) { |
| 161 | + plugin._diag.error('Error ending span', e); |
| 162 | + } |
| 163 | + throw error; |
| 164 | + }); |
| 165 | + }); |
| 166 | + }; |
| 167 | + } |
| 168 | + ); |
| 169 | + } |
| 170 | + |
| 171 | + override enable(): void { |
| 172 | + // Patch the instance passed in via this._config |
| 173 | + this._patchAxios(); |
| 174 | + } |
| 175 | + |
| 176 | + override disable(): void { |
| 177 | + // Unwrap the instance |
| 178 | + this._unwrap(Axios.prototype, 'request'); |
| 179 | + } |
| 180 | +} |
0 commit comments