CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-opentelemetry--sdk-trace-base

Foundational tracing SDK components for OpenTelemetry JavaScript providing manual instrumentation capabilities

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

Overview
Eval results
Files

tracer-provider.mddocs/

Tracer Provider

The tracer provider serves as the central registry and factory for creating tracers with shared configuration across an OpenTelemetry application. It manages the lifecycle of tracers, span processors, and provides controlled shutdown capabilities.

Capabilities

BasicTracerProvider

The main tracer provider implementation that platform libraries can extend. It provides tracer creation, configuration management, and coordinated shutdown of all components.

/**
 * Basic tracer provider which platform libraries can extend
 */
class BasicTracerProvider implements TracerProvider {
  constructor(config?: TracerConfig);
  
  /**
   * Get a tracer with the given name and optional version/schema URL
   * Returns cached tracer for same name/version/schemaUrl combination
   */
  getTracer(name: string, version?: string, options?: { schemaUrl?: string }): Tracer;
  
  /**
   * Force flush all span processors within the configured timeout
   * @returns Promise that resolves when all processors have flushed
   */
  forceFlush(): Promise<void>;
  
  /**
   * Shutdown all active span processors
   * @returns Promise that resolves when shutdown is complete
   */
  shutdown(): Promise<void>;
}

/**
 * Configuration interface for Basic Tracer
 */
interface TracerConfig {
  /** Sampler determines if a span should be recorded or should be a NoopSpan */
  sampler?: Sampler;
  
  /** General Limits for attributes across the trace service */
  generalLimits?: GeneralLimits;
  
  /** Span-specific limits for attributes, events, and links */
  spanLimits?: SpanLimits;
  
  /** Resource associated with trace telemetry */
  resource?: Resource;
  
  /** Generator of trace and span IDs (defaults to random ID generator) */
  idGenerator?: IdGenerator;
  
  /** How long forceFlush can run before being cancelled (default: 30000ms) */
  forceFlushTimeoutMillis?: number;
  
  /** List of SpanProcessors for the tracer */
  spanProcessors?: SpanProcessor[];
}

Usage Examples:

import { BasicTracerProvider, BatchSpanProcessor, ConsoleSpanExporter, AlwaysOnSampler } from '@opentelemetry/sdk-trace-base';
import { Resource } from '@opentelemetry/resources';

// Basic provider setup
const provider = new BasicTracerProvider({
  resource: new Resource({
    'service.name': 'my-service',
    'service.version': '1.0.0',
  }),
  sampler: new AlwaysOnSampler(),
  spanProcessors: [
    new BatchSpanProcessor(new ConsoleSpanExporter())
  ],
  forceFlushTimeoutMillis: 5000
});

// Get tracers with different configurations
const userTracer = provider.getTracer('user-service', '2.1.0');
const orderTracer = provider.getTracer('order-service', '1.5.0', {
  schemaUrl: 'https://opentelemetry.io/schemas/1.21.0'
});

// Graceful shutdown
await provider.forceFlush();
await provider.shutdown();

Configuration Types

Configuration interfaces for setting limits and controlling tracer behavior.

/**
 * Global configuration limits of trace service
 */
interface GeneralLimits {
  /** Maximum allowed attribute value size */
  attributeValueLengthLimit?: number;
  /** Number of attributes per trace */
  attributeCountLimit?: number;
}

/**
 * Span-specific configuration limits
 */
interface SpanLimits {
  /** Maximum allowed attribute value size for spans */
  attributeValueLengthLimit?: number;
  /** Number of attributes per span */
  attributeCountLimit?: number;
  /** Number of links per span */
  linkCountLimit?: number;
  /** Number of message events per span */
  eventCountLimit?: number;
  /** Maximum number of attributes allowed per span event */
  attributePerEventCountLimit?: number;
  /** Maximum number of attributes allowed per span link */
  attributePerLinkCountLimit?: number;
}

/**
 * Configuration for registering the API with the SDK
 */
interface SDKRegistrationConfig {
  /** Propagator to register as the global propagator */
  propagator?: TextMapPropagator | null;
  /** Context manager to register as the global context manager */
  contextManager?: ContextManager | null;
}

Environment Variables:

The tracer provider respects the following environment variables for configuration:

  • OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT - Global attribute value length limit
  • OTEL_ATTRIBUTE_COUNT_LIMIT - Global attribute count limit
  • OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT - Span-specific attribute value length limit
  • OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT - Span-specific attribute count limit
  • OTEL_SPAN_LINK_COUNT_LIMIT - Maximum number of links per span
  • OTEL_SPAN_EVENT_COUNT_LIMIT - Maximum number of events per span
  • OTEL_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT - Max attributes per event
  • OTEL_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT - Max attributes per link

Usage Examples:

// Configuration with limits
const provider = new BasicTracerProvider({
  generalLimits: {
    attributeValueLengthLimit: 1024,
    attributeCountLimit: 64
  },
  spanLimits: {
    attributeValueLengthLimit: 512,
    attributeCountLimit: 32,
    linkCountLimit: 128,
    eventCountLimit: 128,
    attributePerEventCountLimit: 16,
    attributePerLinkCountLimit: 16
  }
});

// With custom resource and sampler
const provider = new BasicTracerProvider({
  resource: new Resource({
    'service.name': 'payment-service',
    'service.namespace': 'production',
    'deployment.environment': 'prod'
  }),
  sampler: new TraceIdRatioBasedSampler(0.1), // 10% sampling
  forceFlushTimeoutMillis: 10000
});

Tracer Implementation

Internal tracer implementation that creates and manages spans (not directly exported but important for understanding behavior).

/**
 * Tracer implementation that creates spans with sampling decisions
 */
interface Tracer {
  /**
   * Start a new span with optional configuration
   */
  startSpan(name: string, options?: SpanOptions, context?: Context): Span;
  
  /**
   * Start an active span and execute a function within its context
   * Multiple overloads support different parameter combinations
   */
  startActiveSpan<F extends (span: Span) => ReturnType<F>>(
    name: string,
    fn: F
  ): ReturnType<F>;
  
  startActiveSpan<F extends (span: Span) => ReturnType<F>>(
    name: string,
    options: SpanOptions,
    fn: F
  ): ReturnType<F>;
  
  startActiveSpan<F extends (span: Span) => ReturnType<F>>(
    name: string,
    options: SpanOptions,
    context: Context,
    fn: F
  ): ReturnType<F>;
  
  /** Get the general limits configuration */
  getGeneralLimits(): GeneralLimits;
  
  /** Get the span limits configuration */
  getSpanLimits(): SpanLimits;
}

Force Flush Behavior

The BasicTracerProvider implements sophisticated force flush behavior with timeout handling.

/**
 * Internal enum for tracking force flush state
 */
enum ForceFlushState {
  'resolved',
  'timeout', 
  'error',
  'unresolved'
}

Force Flush Process:

  1. Calls forceFlush() on all configured span processors
  2. Each processor flush is wrapped with a timeout based on forceFlushTimeoutMillis
  3. If any processor exceeds the timeout, an error is logged but other processors continue
  4. Returns a Promise that resolves when all processors complete or timeout

Usage Examples:

// Force flush with custom timeout handling
try {
  await provider.forceFlush();
  console.log('All spans successfully flushed');
} catch (error) {
  console.error('Some processors failed to flush:', error);
}

// Graceful application shutdown
async function gracefulShutdown() {
  console.log('Starting graceful shutdown...');
  
  try {
    // Force flush pending spans
    await provider.forceFlush();
    
    // Shutdown all processors
    await provider.shutdown();
    
    console.log('Shutdown complete');
  } catch (error) {
    console.error('Shutdown error:', error);
  }
}

process.on('SIGTERM', gracefulShutdown);
process.on('SIGINT', gracefulShutdown);

Install with Tessl CLI

npx tessl i tessl/npm-opentelemetry--sdk-trace-base

docs

index.md

platform.md

samplers.md

span-exporters.md

span-processors.md

tracer-provider.md

tile.json