@@ -30,7 +30,12 @@ import {
30
30
resourceFromAttributes ,
31
31
} from '@opentelemetry/resources' ;
32
32
import { type SpanProcessor } from '@opentelemetry/sdk-trace-base' ;
33
- import { WebTracerProvider } from '@opentelemetry/sdk-trace-web' ;
33
+ import {
34
+ AlwaysOnSampler ,
35
+ ParentBasedSampler ,
36
+ TraceIdRatioBasedSampler ,
37
+ WebTracerProvider ,
38
+ } from '@opentelemetry/sdk-trace-web' ;
34
39
import { unfakePromise } from '@whatwg-node/promise-helpers' ;
35
40
import { YogaLogger } from 'graphql-yoga' ;
36
41
import { ATTR_SERVICE_VERSION , SEMRESATTRS_SERVICE_NAME } from './attributes' ;
@@ -125,6 +130,13 @@ interface OpenTelemetryGatewayPluginOptionsWithInit {
125
130
* - `ContextManager`: rely on this provided `ContextManger` instance.
126
131
*/
127
132
contextManager ?: ContextManager | boolean ;
133
+ /**
134
+ * Sampling rate of spans. The value should be between 0 and 1.
135
+ * By default, all spans are recorded and exported, which correspond to a sampling rate of 1.
136
+ *
137
+ * Note: The sampling strategy used is parent based, meaning spans will be always sampled if a sampled parent span is found in the OTEL context.
138
+ */
139
+ samplingRate ?: number ;
128
140
}
129
141
130
142
type OpenTelemetryGatewayPluginOptionsInit =
@@ -332,14 +344,20 @@ export function useOpenTelemetry(
332
344
333
345
let contextManager$ = getContextManager ( options . contextManager ) ;
334
346
347
+ const sampler = options . samplingRate
348
+ ? new ParentBasedSampler ( {
349
+ root : new TraceIdRatioBasedSampler ( options . samplingRate ) ,
350
+ } )
351
+ : new AlwaysOnSampler ( ) ;
352
+
335
353
setGlobalErrorHandler ( ( err ) => {
336
354
diag . error ( 'Uncaught Error' , err ) ;
337
355
} ) ;
338
356
339
357
return exporters$
340
358
. then ( ( exporters ) => {
341
359
spanProcessors = exporters ;
342
- provider = new WebTracerProvider ( { resource, spanProcessors } ) ;
360
+ provider = new WebTracerProvider ( { resource, spanProcessors, sampler } ) ;
343
361
return contextManager$ ;
344
362
} )
345
363
. then ( ( contextManager ) => {
0 commit comments