Skip to content

Commit

Permalink
feat(instrumentation-xhr): add applyCustomAttributesOnSpan hook (#2134)
Browse files Browse the repository at this point in the history
Co-authored-by: Daniel Dyla <[email protected]>
Co-authored-by: Bartlomiej Obecny <[email protected]>
Co-authored-by: Valentin Marchaud <[email protected]>
  • Loading branch information
4 people authored Apr 25, 2021
1 parent f077df3 commit d504f32
Show file tree
Hide file tree
Showing 2 changed files with 231 additions and 73 deletions.
30 changes: 30 additions & 0 deletions packages/opentelemetry-instrumentation-xml-http-request/src/xhr.ts
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

0 comments on commit d504f32

Please sign in to comment.