CtrlK
BlogDocsLog inGet started
Tessl Logo

dash0/agent-skills

Expert guidance for configuring and deploying the OpenTelemetry Collector. Use when setting up a Collector pipeline, configuring receivers, exporters, or processors, deploying a Collector to Kubernetes or Docker, or forwarding telemetry to Dash0. Triggers on requests involving collector, pipeline, OTLP receiver, exporter, or Dash0 collector setup.

100

Quality

100%

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Advisory

Suggest reviewing before use

Overview
Quality
Evals
Security
Files

ruby.mdskills/otel-instrumentation/rules/sdks/

title:
Ruby Instrumentation
impact:
HIGH
tags:
ruby, backend, server

Ruby Instrumentation

Instrument Ruby applications to generate traces, logs, and metrics for deep insights into behavior and performance.

Use cases

  • HTTP Request Monitoring: Understand outgoing and incoming HTTP requests through traces and metrics, with drill-downs to database level
  • Database Performance: Observe which database statements execute and measure their duration for optimization
  • Error Detection: Reveal uncaught errors and the context in which they happened

Installation

bundle add opentelemetry-sdk opentelemetry-instrumentation-all opentelemetry-exporter-otlp

Note: Installing the gems alone is insufficient—you must initialize the SDK AND enable exporters.

Environment variables

All environment variables that control the SDK behavior:

VariableRequiredDefaultDescription
OTEL_SERVICE_NAMEYesunknown_serviceIdentifies your service in telemetry data
OTEL_TRACES_EXPORTERYesnoneMust set to otlp to export traces
OTEL_METRICS_EXPORTERNononeSet to otlp to export metrics
OTEL_LOGS_EXPORTERNononeSet to otlp to export logs
OTEL_EXPORTER_OTLP_ENDPOINTYeshttp://localhost:4318OTLP collector endpoint
OTEL_EXPORTER_OTLP_HEADERSNo-Headers for authentication (e.g., Authorization=Bearer TOKEN)
OTEL_EXPORTER_OTLP_PROTOCOLNohttp/protobufProtocol: grpc, http/protobuf, or http/json
OTEL_RESOURCE_ATTRIBUTESNo-Additional resource attributes (e.g., deployment.environment=production)

Critical: Without OTEL_TRACES_EXPORTER=otlp, the SDK defaults to none and no telemetry is exported.

Where to get configuration values

  1. OTLP Endpoint: Your observability platform's OTLP endpoint
    • In Dash0: Settings → Organization → Endpoints
    • Format: https://<region>.your-platform.com
  2. Auth Token: API token for telemetry ingestion
  3. Service Name: Choose a descriptive name (e.g., order-api, checkout-service)

Configuration

1. Initialize the SDK

The SDK must be initialized in code on startup, before any application or framework code runs.

Rails projects — create config/initializers/opentelemetry.rb:

require 'opentelemetry/sdk'
require 'opentelemetry/instrumentation/all'
OpenTelemetry::SDK.configure do |c|
  c.use_all()
end

Non-Rails projects — add to your application entry point before any other requires:

require 'opentelemetry/sdk'
require 'opentelemetry/instrumentation/all'
OpenTelemetry::SDK.configure do |c|
  c.use_all()
end

2. Set service name

export OTEL_SERVICE_NAME="my-service"

3. Enable exporters

This step is required - without it, no telemetry is sent:

# Required for traces
export OTEL_TRACES_EXPORTER="otlp"

# Optional: also export metrics and logs
export OTEL_METRICS_EXPORTER="otlp"
export OTEL_LOGS_EXPORTER="otlp"

4. Configure endpoint

export OTEL_EXPORTER_OTLP_ENDPOINT="https://<OTLP_ENDPOINT>"
export OTEL_EXPORTER_OTLP_HEADERS="Authorization=Bearer YOUR_AUTH_TOKEN"

5. Optional: target specific dataset

export OTEL_EXPORTER_OTLP_HEADERS="Authorization=Bearer YOUR_AUTH_TOKEN,Dash0-Dataset=my-dataset"

Complete setup

Using environment variables

# Service identification
export OTEL_SERVICE_NAME="my-service"

# Enable exporters (required!)
export OTEL_TRACES_EXPORTER="otlp"
export OTEL_METRICS_EXPORTER="otlp"
export OTEL_LOGS_EXPORTER="otlp"

# Configure endpoint
export OTEL_EXPORTER_OTLP_ENDPOINT="https://<OTLP_ENDPOINT>"
export OTEL_EXPORTER_OTLP_HEADERS="Authorization=Bearer YOUR_AUTH_TOKEN"

bundle exec rails server

Using .env file with dotenv

Add the dotenv gem and create a .env file:

.env:

OTEL_SERVICE_NAME=my-service
OTEL_TRACES_EXPORTER=otlp
OTEL_METRICS_EXPORTER=otlp
OTEL_LOGS_EXPORTER=otlp
OTEL_EXPORTER_OTLP_ENDPOINT=https://<OTLP_ENDPOINT>
OTEL_EXPORTER_OTLP_HEADERS=Authorization=Bearer YOUR_AUTH_TOKEN

Run with:

bundle exec rails server

Local development

Console exporter

For development without a collector, use the console exporter to see telemetry in your terminal:

export OTEL_SERVICE_NAME="my-service"
export OTEL_TRACES_EXPORTER="console"
export OTEL_METRICS_EXPORTER="console"
export OTEL_LOGS_EXPORTER="console"

bundle exec rails server

This prints spans, metrics, and logs directly to stdout—useful for verifying instrumentation works before configuring a remote backend.

Without a collector

If you set OTEL_TRACES_EXPORTER=otlp but have no collector running, you will see connection errors. This is expected behavior.

Options:

  1. Use console exporter during development (recommended for quick testing)
  2. Run a local OpenTelemetry Collector
  3. Point directly to your observability backend

Resource configuration

Set service.name, service.version, and deployment.environment.name for every deployment. See resource attributes for the full list of required and recommended attributes.

Kubernetes setup

See Kubernetes deployment for pod metadata injection, resource attributes, and Dash0 Kubernetes Operator guidance.

Supported libraries

The auto-instrumentation package automatically instruments:

CategoryLibraries
HTTPRack, Rails, Sinatra, Faraday, Net::HTTP
DatabasePG, MySQL2, ActiveRecord
CacheRedis, Dalli
MessagingSidekiq, Resque, Bunny
ExternalRestClient, Ethon, HTTP.rb
GraphQLGraphQL
LoggingLogger

Refer to the OpenTelemetry Ruby Contrib repository for the complete list.

Custom spans

Add business context to auto-instrumented traces:

tracer = OpenTelemetry.tracer_provider.tracer('my-service')

def process_order(order)
  tracer = OpenTelemetry.tracer_provider.tracer('my-service')
  tracer.in_span('order.process') do |span|
    span.set_attribute('order.id', order.id)
    span.set_attribute('order.total', order.total)
    result = save_order(order)
    result
  rescue StandardError => e
    span.status = OpenTelemetry::Trace::Status.error(e.message)
    ctx = span.context
    logger.error('order.process.failed',
      trace_id: ctx.hex_trace_id,
      span_id: ctx.hex_span_id,
      'exception.type': e.class.name,
      'exception.message': e.message,
      'exception.stacktrace': e.backtrace&.join("\n"))
    raise
  end
end

Retrieving the active span

Auto-instrumentation creates spans you do not control directly (e.g., the SERVER span for an HTTP request). To enrich these spans with business context or set their status, retrieve the active span from the current context. See adding attributes to auto-instrumented spans for when to use this pattern.

span = OpenTelemetry::Trace.current_span
span.set_attribute('order.id', params[:order_id])
span.set_attribute('tenant.id', request.headers['X-Tenant-Id'])

OpenTelemetry::Trace.current_span returns a non-recording span if no span is active. Calling set_attribute or status= on a non-recording span is a no-op, so no guard is needed.

Span status rules

See span status code for the full rules. This section shows how to apply them in Ruby.

Always include a status message with ERROR

The argument to Status.error is the status message. It must contain the error class and a short explanation — enough to understand the failure without opening the full trace.

# BAD: no status message
span.status = OpenTelemetry::Trace::Status.error

# BAD: generic message with no diagnostic value
span.status = OpenTelemetry::Trace::Status.error('something went wrong')

# GOOD: specific message with error class and context
span.status = OpenTelemetry::Trace::Status.error("#{e.class}: #{e.message}")

Do not include backtraces in the status message. Record those in a log record with exception.stacktrace instead.

# BAD: backtrace in the status message
span.status = OpenTelemetry::Trace::Status.error(e.full_message)

# GOOD: short message only
span.status = OpenTelemetry::Trace::Status.error(e.message)

Use OK only for confirmed success

Set status to OK when application logic has explicitly verified the operation succeeded. Leave status UNSET if the code simply did not encounter an error.

# GOOD: explicit confirmation from downstream
response = Net::HTTP.get_response(uri)
if response.is_a?(Net::HTTPSuccess)
  span.status = OpenTelemetry::Trace::Status.ok
end

# BAD: setting OK speculatively
span.status = OpenTelemetry::Trace::Status.ok
some_method # might still fail after this point

Structured logging

Configure your logging framework to serialize exceptions into a single structured field so that stack traces do not break the one-line-per-record contract. See logs for general guidance on structured logging and exception stack traces.

Semantic Logger

semantic_logger produces single-line JSON with exceptions serialized into structured fields.

require 'semantic_logger'

SemanticLogger.add_appender(io: $stdout, formatter: :json)
logger = SemanticLogger['OrderService']

begin
  process_order(order)
rescue StandardError => e
  logger.error('order.failed', exception: e, order_id: order.id)
end

The JSON formatter serializes the exception class, message, and backtrace into structured fields, keeping each log record on a single line.

Lograge (Rails)

For Rails applications, lograge replaces the default multi-line request log with a single-line JSON entry.

# config/environments/production.rb
config.lograge.enabled = true
config.lograge.formatter = Lograge::Formatters::Json.new

Lograge does not handle exception backtraces directly. Pair it with semantic_logger or a JSON formatter that serializes exceptions as single-line fields.

Graceful shutdown

The Ruby SDK does not register shutdown hooks automatically. Register an at_exit hook to flush and shut down providers before the process terminates, so buffered spans, metrics, and log records are not lost.

at_exit do
  OpenTelemetry.tracer_provider.shutdown if OpenTelemetry.respond_to?(:tracer_provider)
  OpenTelemetry.meter_provider.shutdown if OpenTelemetry.respond_to?(:meter_provider)
  OpenTelemetry.logger_provider.shutdown if OpenTelemetry.respond_to?(:logger_provider)
end

Place the at_exit block immediately after OpenTelemetry::SDK.configure in your initializer. shutdown flushes pending batches and releases resources. The call blocks until export completes or the timeout expires (default 30 seconds).

Troubleshooting

No telemetry appearing

Check exporters are enabled:

echo $OTEL_TRACES_EXPORTER  # Should be "otlp" or "console", not empty

The SDK defaults OTEL_TRACES_EXPORTER to none, which silently discards all telemetry.

Verify SDK is initialized: Ensure the OpenTelemetry::SDK.configure block runs before your application code. In Rails, this means placing it in config/initializers/opentelemetry.rb.

Connection errors

This means the SDK is working but cannot reach the collector:

  • No collector running: Start a local collector or use OTEL_TRACES_EXPORTER=console
  • Wrong endpoint: Check OTEL_EXPORTER_OTLP_ENDPOINT is correct
  • Port mismatch: gRPC uses 4317, HTTP uses 4318

Instrumentation not picking up libraries

Ensure c.use_all() is called inside the OpenTelemetry::SDK.configure block. Verify that the opentelemetry-instrumentation-all gem is installed. Some libraries require their instrumentation gem to be explicitly added to the Gemfile.

"Exporter is empty" or similar warnings

Usually means OTEL_TRACES_EXPORTER (or metrics/logs) is not set. Set it explicitly:

export OTEL_TRACES_EXPORTER="otlp"

Resources

skills

README.md

tile.json