### Initialize SDK via OTEL_CONFIG_FILE Environment Variable (Shell Example) Source: https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/configuration/sdk.md This example shows how to set the OTEL_CONFIG_FILE environment variable to initialize OpenTelemetry components. This method offers a convenient way to configure the SDK without extensive code changes, particularly in languages like Java. ```shell # Example for setting the environment variable in a shell export OTEL_CONFIG_FILE=/path/to/your/otel-config.yaml ``` -------------------------------- ### Install Node.js LTS Source: https://github.com/open-telemetry/opentelemetry-specification/blob/main/CONTRIBUTING.md Install the latest LTS release of Node.js using nvm. This is a prerequisite for using the project's tooling. ```bash nvm install --lts ``` -------------------------------- ### Example Diff Schema Output Source: https://github.com/open-telemetry/opentelemetry-specification/blob/main/oteps/4815-semantic-conventions-schema-v2.md An example of the machine-readable summary of changes between semantic convention registry versions, formatted as YAML. ```yaml schema_url: https://opentelemetry.io/schemas/semconv/1.39.0 registry: attribute_changes: - name: system.memory.linux.slab.state type: added - new_name: rpc.response.status_code old_name: rpc.connect_rpc.error_code type: renamed ... ``` -------------------------------- ### Example Schema File Configuration Source: https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/schemas/file_format_v1.0.0.md An example of an OpenTelemetry schema file demonstrating the 'file_format' setting and 'schema_url'. The 'file_format' indicates the version of the schema file's structure, while 'schema_url' points to the published schema version. ```yaml # Defines the file format. MUST be set to 1.0.0. file_format: 1.0.0 # The Schema URL that this file is published at. The version number in the URL # MUST match the highest version number in the "versions" section below. # Note: the schema version number in the URL is not related in any way to # the file_format setting above. schema_url: https://opentelemetry.io/schemas/1.1.0 # Definitions for each schema version in this family. # Note: the ordering of versions is defined according to semver ``` -------------------------------- ### Example Composable Sampler Configuration Source: https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/trace/sdk.md This example demonstrates how to create a composite sampler configuration using various built-in ComposableSamplers. It sets up rules for health checks, checkout endpoints, and general spans, and then uses a parent-based sampler for child spans. ```java rootSampler = ComposableRuleBased([ (isHealthCheck, ComposableAlwaysOff), (isCheckout, ComposableAlwaysOn), (isAnything, ComposableTraceIDRatio(0.1)) ]) finalSampler = ComposableParentThreshold(rootSampler) ``` -------------------------------- ### Initialize Metric Instruments Source: https://github.com/open-telemetry/opentelemetry-specification/blob/main/oteps/metrics/0049-metric-label-set.md Example of defining cumulative and gauge instruments in Go for use with the Metrics API. ```golang var ( cumulative = metric.NewFloat64Cumulative("my_counter") gauge = metric.NewFloat64Gauge("my_gauge") ) ``` -------------------------------- ### Example Manifest for Schema URL Source: https://github.com/open-telemetry/opentelemetry-specification/blob/main/oteps/4815-semantic-conventions-schema-v2.md This YAML snippet shows an example of a manifest that a service should return when a valid Schema URL is requested via HTTP GET. It includes the file format version and the primary schema URL, which defines the schema family and version. ```yaml file_format: manifest/2.0 schema_url: https://opentelemetry.io/schemas/semconv-dev/1.40.0-dev ``` -------------------------------- ### Example SDK Configuration Source: https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/configuration/sdk.md This YAML snippet shows a basic configuration for a TracerProvider with a batch span processor and an OTLP HTTP exporter. ```yaml file_format: 1.0 tracer_provider: processors: - batch: exporter: otlp_http: ``` -------------------------------- ### Explicit Context Propagation - TypeScript Source: https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/compatibility/opentracing.md Demonstrates how a Tracer Shim in TypeScript handles explicit context propagation when starting a new span. It avoids using implicit propagation by not getting or setting the current context if no 'childOf' or 'references' are provided in the options, setting 'root' to true. ```typescript // Tracer Shim startSpan(name: string, options: SpanOptions = {}): Span { const otelSpanOptions = ...; if (!options.childOf && !options.references) { // Do NOT get nor set the current Context/Span, // as it is part of the implicit propagation support. otelSpanOptions.root = true; } ... } ``` -------------------------------- ### Go: Setup Logger Provider with Custom Processors Source: https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/logs/supplementary-guidelines.md Demonstrates setting up a logger provider using custom processors like IsolatedProcessor and LogEventRouteProcessor. It configures OTLP export for events and stdout export for logs, with specific severity and redaction rules. ```go import ( "context" "go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploghttp" "go.opentelemetry.io/otel/exporters/stdout/stdoutlog" "go.opentelemetry.io/otel/log" sdklog "go.opentelemetry.io/otel/sdk/log" ) // NewLoggerProvider creates a new logger provider. // - Event records with severity not lower than Info are exported via OTLP. // - Event records have token attributes redacted. // - Non-event log records with severity not lower than Debug are synchronously emitted to stdout. func NewLoggerProvider() (*sdklog.LoggerProvider, error) { // Events processing setup. otlpExp, err := otlploghttp.New(context.Background()) if err != nil { return nil, err } evtProc := &SeverityProcessor{ // This processing is isolated so that there is no chance // that log records send to stdout have their token attributes redacted. Processor: &IsolatedProcessor{ Processors: []sdklog.Processor{ &RedactTokensProcessor{}, sdklog.NewBatchProcessor(otlpExp), }, }, Min: log.SeverityInfo, } // Logs processing setup. stdoutExp, err := stdoutlog.New() if err != nil { return nil, err } logProc := &SeverityProcessor{ Processor: sdklog.NewSimpleProcessor(stdoutExp), Min: log.SeverityDebug, } // Create logs provider with log/event routing. provider := sdklog.NewLoggerProvider( sdklog.WithProcessor(&LogEventRouteProcessor{ LogProcessor: logProc, EventProcessor: evtProc, }), ) return provider, nil } ``` -------------------------------- ### LabelSet API Usage Examples Source: https://github.com/open-telemetry/opentelemetry-specification/blob/main/oteps/metrics/0049-metric-label-set.md Examples demonstrating how to use the LabelSet API for efficient label management in OpenTelemetry Metrics. ```APIDOC ## LabelSet API Usage Examples ### Description Examples demonstrating how to use the `LabelSet` API for efficient label management in OpenTelemetry Metrics, reducing the cost of label serialization. ### Method N/A (Conceptual API examples) ### Endpoint N/A ### Parameters N/A ### Request Example ```golang // Assume meter is an initialized Meter instance // Example 1: Using LabelSet to construct multiple Handles var ( cumulative = metric.NewFloat64Cumulative("my_counter") gauge = metric.NewFloat64Gauge("my_gauge") ) var ( labels = meter.Labels({ "required_key1": value1, "required_key2": value2 }) chandle = cumulative.GetHandle(labels) ghandle = gauge.GetHandle(labels) ) // In a loop or other context: // chandle.Add(...) // ghandle.Set(...) // Example 2: Using LabelSet for multiple Direct calls labels := meter.Labels({ "required_key1": value1, "required_key2": value2 }) cumulative.Add(quantity, labels) gauge.Set(quantity, labels) // Example 3: Ordered LabelSet construction (language-optional) var rpcLabelKeys = meter.OrderedLabelKeys("a", "b", "c") for _, input := range stream { labels := rpcLabelKeys.Values(1, 2, 3) // a=1, b=2, c=3 // Use labels... } ``` ### Response N/A ### Response Example N/A ``` -------------------------------- ### Parse and Create SDK Components from Configuration File (Java) Source: https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/configuration/sdk.md This snippet demonstrates parsing a YAML configuration file and using the result to create SDK components. It shows a basic scenario for initializing OpenTelemetry. ```java OpenTelemetry openTelemetry = OpenTelemetry.noop(); try { // Parse configuration file to configuration model OpenTelemetryConfiguration configurationModel = parse(new File("/app/sdk-config.yaml")); // Create SDK components from configuration model openTelemetry = create(configurationModel); } catch (Throwable e) { log.error("Error initializing SDK from configuration file", e); } // Access SDK components and install instrumentation TracerProvider tracerProvider = openTelemetry.getTracerProvider(); MeterProvider meterProvider = openTelemetry.getMeterProvider(); LoggerProvider loggerProvider = openTelemetry.getLoggerProvider(); ContextPropagators propagators = openTelemetry.getPropagators(); ConfigProvider configProvider = openTelemetry.getConfigProvider(); ``` -------------------------------- ### Usage Examples Source: https://github.com/open-telemetry/opentelemetry-specification/blob/main/oteps/0201-scope-attributes.md Provides pseudocode examples demonstrating the usage of LogEmitter with scope attributes for client-side logging and log record multiplexing. ```APIDOC ## Usage Examples ### Description This section provides pseudocode examples illustrating how to use `LogEmitter` with scope attributes. The first example shows obtaining loggers with specific attributes for client-side events. The second example demonstrates log record multiplexing using scope attributes for different data types like profiling data, client-side events, and regular logs. ### Method N/A (Code Examples) ### Endpoint N/A (Code Examples) ### Parameters N/A (Code Examples) ### Request Example ```java // Obtain loggers once, at startup. appLogger = LogEmitterProvider.GetLogEmitter("mylibrary", "1.0.0") loggerForUserEvents = LogEmitterProvider.GetLogEmitter("mylibrary", "1.0.0", KeyValue("otel.clientside", true)) // Somewhere later in the code when the user clicks a UI element. This should // export telemetry with otel.clientside=true Scope attribute set. loggerForUserEvents.emit(LogRecord{Body:"click", Attributes:...}) // Somewhere else in the code, not related to user interactions. This should // export telemetry without any Scope attributes. appLogger.emit(LogRecord{Body:"Error occurred while processing the file", Attributes:...}) ``` ### Response #### Success Response (200) N/A (Code Examples) #### Response Example ![LogRecord Multiplexing](img/0201-scope-multiplexing.png) ``` -------------------------------- ### POST /configurer/create Source: https://github.com/open-telemetry/opentelemetry-specification/blob/main/oteps/0225-configuration.md Initializes a Configurer instance from a provided configuration model to generate SDK components. ```APIDOC ## POST /configurer/create ### Description Creates a Configurer instance that interprets a Configuration model to produce SDK components like TracerProvider, MeterProvider, and LoggerProvider. ### Method POST ### Endpoint /configurer/create ### Parameters #### Request Body - **config** (object) - Required - A validated Configuration model object. ### Request Example { "config": { "service_name": "my-service" } } ### Response #### Success Response (200) - **configurer_id** (string) - Identifier for the created Configurer instance. #### Response Example { "configurer_id": "cfg-12345" } ``` -------------------------------- ### Environment Variable Substitution in Configuration Source: https://github.com/open-telemetry/opentelemetry-specification/blob/main/oteps/0225-configuration.md This example demonstrates how configuration files support environment variable expansion. Sensitive data like API keys can be securely injected into the configuration. Implementations must perform this substitution before parsing, and raise an error if an undefined variable is referenced. ```yaml sdk: tracer_provider: exporters: otlp: endpoint: https://example.host:4317/v1/traces headers: api-key: ${env:API_KEY} ``` -------------------------------- ### Go: Throttling and RetryInfo Example Source: https://github.com/open-telemetry/opentelemetry-specification/blob/main/oteps/0156-columnar-encoding.md Illustrates how a client might handle throttling signals from a server using gRPC UNAVAILABLE errors and the `retry_info` attribute, including exponential backoff logic. ```go package main import ( "context" "fmt" "log" "math" "time" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" ) // Mock RetryInfo structure as described in the spec. type RetryInfo struct { RetryDelay time.Duration } // Simulate receiving an error response from the server. func simulateServerResponse(shouldThrottle bool) error { if shouldThrottle { // Simulate server signaling throttling with UNAVAILABLE and retry_info retryInfo := RetryInfo{RetryDelay: 5 * time.Second} // Example delay return status.Error(codes.Unavailable, "server temporarily unavailable") // In a real gRPC response, retry_info would be in the message payload. // For this simulation, we'll just return the error. } return nil // Success } // Exponential backoff parameters const ( initialRetryDelay = 1 * time.Second maxRetryDelay = 60 * time.Second backoffFactor = 2.0 ) func main() { ctx := context.Background() var currentRetryDelay = initialRetryDelay maxRetries := 5 for attempt := 0; attempt < maxRetries; attempt++ { log.Printf("Attempt %d: Sending request...\n", attempt+1) // Simulate sending data and receiving a response // For demonstration, let's assume the server throttles on the first attempt. err := simulateServerResponse(attempt == 0) if err == nil { log.Println("Request successful!") return // Success, exit loop } // Check if the error is due to throttling (UNAVAILABLE) if s, ok := status.FromError(err); ok && s.Code() == codes.Unavailable { log.Printf("Received throttling error: %v\n", err) // Extract retry delay if available (simulated here) var retryInfo RetryInfo // In a real scenario, you'd parse this from the error details. // For simulation, we use the value from simulateServerResponse. if attempt == 0 { // Only apply if it's the first throttling error retryInfo.RetryDelay = 5 * time.Second } // Determine the delay for the next retry var delay time.Duration if retryInfo.RetryDelay > 0 { // Use server-suggested delay, capped by maxRetryDelay delay = time.Min(retryInfo.RetryDelay, maxRetryDelay) } else { // Use exponential backoff based on currentRetryDelay delay = time.Min(currentRetryDelay, maxRetryDelay) currentRetryDelay = time.Duration(float64(currentRetryDelay) * backoffFactor) } log.Printf("Waiting for %s before retrying...\n", delay) select { case <-time.After(delay): // Continue to the next iteration case <-ctx.Done(): log.Println("Context cancelled, stopping retries.") return } } else { // Handle other types of errors log.Printf("Received non-throttling error: %v\n", err) return // Non-retryable error } } log.Println("Max retries reached, failing the request.") } ``` -------------------------------- ### OnStart Source: https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/trace/sdk.md Called synchronously when a span is started. It receives the started span and its parent context. Implementations should avoid blocking or throwing exceptions. ```APIDOC ## OnStart ### Description Called synchronously on the thread that started the span. This method should not block or throw exceptions. If multiple SpanProcessors are registered, their OnStart callbacks are invoked in the order they have been registered. ### Parameters * `span` - A read/write span object for the started span. Updates to this span should be reflected in the object. * `parentContext` - The parent `Context` of the span determined by the SDK. ### Returns `Void` ``` -------------------------------- ### Creating a Tracer with Resource Information Source: https://github.com/open-telemetry/opentelemetry-specification/blob/main/oteps/0016-named-tracers.md Illustrates creating a Resource object containing the instrumentation library's name and version, and then using this Resource to obtain a Tracer from the TracerProvider. ```java Map libraryLabels = new HashMap<>(); libraryLabels.put("name", "io.opentelemetry.contrib.mongodb"); libraryLabels.put("version", "1.0.0"); Resource libraryResource = Resource.create(libraryLabels); Tracer tracer = OpenTelemetry.getTracerProvider().getTracer(libraryResource); ``` -------------------------------- ### Profile Signal Payload Examples Source: https://github.com/open-telemetry/opentelemetry-specification/blob/main/oteps/profiles/0239-profiles-data-model.md Illustrates example payloads for the Profile Signal, including a simple folded format and the resulting OTLP format. ```APIDOC ### Example Payloads #### Simple Example Considering the following example presented in a modified folded format: ``` foo;bar;baz 100 region=us,trace_id=0x01020304010203040102030401020304,span_id=0x9999999999999999 1687841528000000 foo;bar 200 region=us ``` It represents 2 samples: * one for stacktrace `foo;bar;baz` with value `100`, attributes `region=us`, linked to trace `0x01020304010203040102030401020304` and span `0x9999999999999999`, and timestamp `1687841528000000` * one for stacktrace `foo;bar` with value `200`, attributes `region=us`, no link, no timestamp The resulting profile in OTLP format would look like this (converted to YAML format for legibility): ```yaml resource_profiles: - resource: attributes: null schema_url: todo scope_profiles: - profiles: - profile_id: 0x0102030405060708090a0b0c0d0e0f10 start_time_unix_nano: 1687841520000000 end_time_unix_nano: 1687841530000000 profile: sample_type: type: 4 unit: 5 aggregation_temporality: 1 attribute_table: - key: trace_id value: Value: bytes_value: 0x01020304010203040102030401020304 - key: span_id value: Value: bytes_value: 0x9999999999999999 - key: region value: Value: string_value: us function: - name: 1 - name: 2 - name: 3 location: - line: - function_index: 0 - line: - function_index: 1 - line: - function_index: 2 location_indices: - 0 - 1 - 2 sample: - locations_start_index: 0 locations_length: 3 timestamps: - 1687841528000000 value: - 100 - locations_start_index: 0 locations_length: 2 value: - 200 string_table: - "" - foo - bar - baz - cpu - samples ``` -------------------------------- ### Attribute Collection Examples (JSON) Source: https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/common/README.md Examples of how attribute collections can be represented as JSON objects for non-OTLP protocols. These demonstrate empty, simple, null, array, and nested values. ```json {} ``` ```json {"http.request.method": "GET", "retries": 3} ``` ```json {"payload": "aGVsbG8gd29ybGQ=", "session.id": null} ``` ```json {"colors": ["red", "blue"], "context": {"nested": true}} ``` -------------------------------- ### Simple Reservoir Sampling Algorithm Example Source: https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/metrics/sdk.md Illustrates the logic for a simple reservoir sampling algorithm used by SimpleFixedSizeExemplarReservoir. The number of measurements seen is reset each collection cycle. ```pseudocode if num_measurements_seen < num_buckets then bucket = num_measurements_seen else bucket = random_integer(0, num_measurements_seen) end if bucket < num_buckets then reservoir[bucket] = measurement end num_measurements_seen += 1 ``` -------------------------------- ### OpenTelemetry Schema YAML Example Source: https://github.com/open-telemetry/opentelemetry-specification/blob/main/oteps/0152-telemetry-schemas.md An example of the OpenTelemetry schema file format, showing the schema URL and version information. This format is used to define the structure for telemetry data. ```yaml file_format: 1.0.0 schema_url: https://opentelemetry.io/schemas/1.2.0 versions: 1.2.0: ``` -------------------------------- ### OTLP Profile Payload Example Source: https://github.com/open-telemetry/opentelemetry-specification/blob/main/oteps/profiles/0239-profiles-data-model.md An example of a profile represented in OTLP format, converted to YAML for legibility. It demonstrates the use of string tables, attribute tables, and index-based location referencing. ```yaml resource_profiles: - resource: attributes: null schema_url: todo scope_profiles: - profiles: - profile_id: 0x0102030405060708090a0b0c0d0e0f10 start_time_unix_nano: 1687841520000000 end_time_unix_nano: 1687841530000000 profile: sample_type: type: 4 unit: 5 aggregation_temporality: 1 attribute_table: - key: trace_id value: Value: bytes_value: 0x01020304010203040102030401020304 - key: span_id value: Value: bytes_value: 0x9999999999999999 - key: region value: Value: string_value: us function: - name: 1 - name: 2 - name: 3 location: - line: - function_index: 0 - line: - function_index: 1 - line: - function_index: 2 location_indices: - 0 - 1 - 2 sample: - locations_start_index: 0 locations_length: 3 timestamps: - 1687841528000000 value: - 100 - locations_start_index: 0 locations_length: 2 value: - 200 string_table: - "" - foo - bar - baz - cpu - samples ``` -------------------------------- ### Merge and Create SDK Components from Multiple Configuration Files (Java) Source: https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/configuration/sdk.md This snippet illustrates a more complex configuration scenario involving parsing multiple configuration files, merging them with custom logic, and then creating SDK components from the merged model. This is useful for combining settings from different sources. ```java OpenTelemetry openTelemetry = OpenTelemetry.noop(); try { // Parse local and remote configuration files to configuration models OpenTelemetryConfiguration localConfigurationModel = parse(new File("/app/sdk-config.yaml")); OpenTelemetryConfiguration remoteConfigurationModel = parse(getRemoteConfiguration("http://example-host/config/my-application")); // Merge the configuration models using custom logic OpenTelemetryConfiguration resolvedConfigurationModel = merge(localConfigurationModel, remoteConfigurationModel); // Create SDK components from resolved configuration model openTelemetry = create(resolvedConfigurationModel); } catch (Throwable e) { log.error("Error initializing SDK from configuration file", e); } // Access SDK components and install instrumentation TracerProvider tracerProvider = openTelemetry.getTracerProvider(); MeterProvider meterProvider = openTelemetry.getMeterProvider(); LoggerProvider loggerProvider = openTelemetry.getLoggerProvider(); ContextPropagators propagators = openTelemetry.getPropagators(); ConfigProvider configProvider = openTelemetry.getConfigProvider(); ```