Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(instrumentation-xhr): add applyCustomAttributesOnSpan hook #2134

Merged
merged 10 commits into from
Apr 25, 2021
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import {
isWrapped,
InstrumentationBase,
InstrumentationConfig,
safeExecuteInTheMiddle,
} from '@opentelemetry/instrumentation';
import { hrTime, isUrlIgnored, otperformance } from '@opentelemetry/core';
import { SemanticAttributes } from '@opentelemetry/semantic-conventions';
Expand All @@ -45,6 +46,11 @@ import { AttributeNames } from './enums/AttributeNames';
// safe enough
const OBSERVER_WAIT_TIME_MS = 300;

export type XHRCustomAttributeFunction = (
span: api.Span,
xhr: XMLHttpRequest
) => void;

/**
* XMLHttpRequest config
*/
Expand All @@ -64,6 +70,8 @@ export interface XMLHttpRequestInstrumentationConfig
* also not be traced.
*/
ignoreUrls?: Array<string | RegExp>;
/** Function for adding custom attributes on the span */
applyCustomAttributesOnSpan?: XHRCustomAttributeFunction;
}

/**
Expand Down Expand Up @@ -171,6 +179,24 @@ export class XMLHttpRequestInstrumentation extends InstrumentationBase<XMLHttpRe
}
}

private _applyAttributesAfterXHR(span: api.Span, xhr: XMLHttpRequest) {
const applyCustomAttributesOnSpan = this._getConfig()
.applyCustomAttributesOnSpan;
if (typeof applyCustomAttributesOnSpan === 'function') {
safeExecuteInTheMiddle(
() => applyCustomAttributesOnSpan(span, xhr),
error => {
if (!error) {
return;
}

api.diag.error('applyCustomAttributesOnSpan', error);
},
true
);
}
}

/**
* will collect information about all resources created
* between "send" and "end" with additional waiting for main resource
Expand Down Expand Up @@ -398,6 +424,10 @@ export class XMLHttpRequestInstrumentation extends InstrumentationBase<XMLHttpRe
xhrMem.status = xhr.status;
xhrMem.statusText = xhr.statusText;
plugin._xhrMem.delete(xhr);

if (xhrMem.span) {
plugin._applyAttributesAfterXHR(xhrMem.span, xhr);
}
const endTime = hrTime();

// the timeout is needed as observer doesn't have yet information
Expand Down
Loading