Ruby (OpenTelemetry)
It adds OpenTelemetry to your Ruby service and checks that data arrives. How the setup skill works
Instrument a Ruby service with the OpenTelemetry Ruby SDK and export traces, logs and metrics to Traceway over OTLP/HTTP.
The example is a Sinatra app on Puma. The request spans, the route names and the status codes come from the instrumentation gems, so the only OpenTelemetry code is one small file that starts the SDK. Rails uses the same gems and the same file. See Rails.
Requirements
- Ruby 3.3 or newer and Bundler. The current
opentelemetry-sdkgem requires 3.3. - A Traceway project created with framework OpenTelemetry, and that project's token.
Install
Add the OpenTelemetry gems to your Gemfile:
source "https://rubygems.org"
gem "sinatra", "~> 4.2"
gem "puma", "~> 8.1"
gem "rackup", "~> 2.3"
# Traces
gem "opentelemetry-sdk", "~> 1.13"
gem "opentelemetry-exporter-otlp", "~> 0.37"
gem "opentelemetry-instrumentation-all", "~> 0.102"
# Metrics
gem "opentelemetry-metrics-sdk", "~> 0.22"
gem "opentelemetry-exporter-otlp-metrics", "~> 0.15"
# Logs
gem "opentelemetry-logs-sdk", "~> 0.8"
gem "opentelemetry-exporter-otlp-logs", "~> 0.7"
gem "opentelemetry-instrumentation-logger", "~> 0.5"bundle installTraces are stable in Ruby. Metrics and logs are separate gems that are still on 0.x versions, and the OpenTelemetry project marks both as in development. They work with Traceway today. If you only want traces, leave out the last five gems and their require lines below.
opentelemetry-instrumentation-logger is the bridge from Ruby's Logger to OpenTelemetry. It is not part of opentelemetry-instrumentation-all, so it needs its own line.
Configure
The SDK reads all of this from the process environment.
export OTEL_SERVICE_NAME=my-ruby-service
export OTEL_RESOURCE_ATTRIBUTES="service.version=1.0.0"
export OTEL_EXPORTER_OTLP_ENDPOINT=https://cloud.tracewayapp.com/api/otel
export OTEL_EXPORTER_OTLP_HEADERS="Authorization=Bearer your-project-token"
export OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE=deltaOTEL_EXPORTER_OTLP_ENDPOINTtakes the base URL. The exporters append/v1/traces,/v1/metricsand/v1/logsthemselves.OTEL_SERVICE_NAMEbecomes the Server Name on every endpoint, task and issue. Version travels inOTEL_RESOURCE_ATTRIBUTES. There is noOTEL_SERVICE_VERSIONvariable.- The temporality line makes counters send what changed since the last export, not the running total. Write
deltain lower case. Other spellings fall back to cumulative without a warning. - The Ruby exporters speak OTLP/HTTP with protobuf and nothing else, which is what Traceway accepts. Leave
OTEL_EXPORTER_OTLP_PROTOCOLunset. Setting it togrpcorhttp/jsonswitches traces and logs off with one warning at boot.
Check the path. If the endpoint is your server's address without
/api/otel, the dashboard answers the export with200and a web page. The trace and metric exporters take that as success, so nothing is stored and nothing is logged. A wrong token printsOTLP exporter received rpc.Status{message=, details=[]}, which is the 401.
Start the SDK
# frozen_string_literal: true
require "opentelemetry/sdk"
require "opentelemetry/exporter/otlp"
require "opentelemetry-metrics-sdk"
require "opentelemetry-exporter-otlp-metrics"
require "opentelemetry-logs-sdk"
require "opentelemetry-exporter-otlp-logs"
require "opentelemetry/instrumentation/all"
require "opentelemetry-instrumentation-logger"
OpenTelemetry::SDK.configure do |c|
c.use_all
end
at_exit do
OpenTelemetry.tracer_provider.shutdown
OpenTelemetry.meter_provider.shutdown
OpenTelemetry.logger_provider.shutdown
endTwo things in this file matter more than they look:
- Load order.
use_allonly instruments libraries that are already loaded. Require your web framework before this file. If the SDK is configured first, you get no request spans and no warning. - The
at_exitblock. Spans are sent every 5 seconds, logs every second and metrics every 60. Without the shutdown calls, a process that exits loses what is still queued. A short script that records a metric and exits at once should also callOpenTelemetry.meter_provider.force_flushbefore the shutdown.
Instrument the Server
# frozen_string_literal: true
require "json"
require "logger"
require "sinatra/base"
require_relative "otel"
class App < Sinatra::Base
LOGGER = Logger.new($stdout)
LOGGER.formatter = proc { |_severity, _time, _progname, msg| "#{msg}\n" }
TRACER = OpenTelemetry.tracer_provider.tracer("my-ruby-service", "1.0.0")
METER = OpenTelemetry.meter_provider.meter("my-ruby-service", version: "1.0.0")
SESSIONS_CLEANED = METER.create_counter(
"app.sessions_cleaned", unit: "{session}", description: "Expired sessions removed by the cleanup job"
)
get "/users/:id" do
LOGGER.info("looking up user #{params[:id]}")
user = TRACER.in_span("load-user", attributes: { "user.id" => params[:id] }) do
{ id: params[:id], name: "User #{params[:id]}" }
end
content_type :json
JSON.generate(user)
end
get "/boom" do
raise "boom: something went wrong"
end
get "/run-job" do
OpenTelemetry::Context.with_current(OpenTelemetry::Context::ROOT) do
TRACER.in_span("cleanup-expired-sessions", kind: :consumer) do
SESSIONS_CLEANED.add(7, attributes: { "job" => "cleanup-expired-sessions" })
end
end
content_type :json
JSON.generate(cleaned: 7)
end
endrequire_relative "app"
run AppRun it with the variables from Configure set:
APP_ENV=production bundle exec puma --port 8080 config.ruWhat Arrives With No Application Code
| Traceway | Where it comes from |
|---|---|
| Endpoints, grouped by route pattern | The Rack instrumentation creates the request span, and the Sinatra instrumentation names it from the matched route: GET /users/:id |
| Status codes, including 500 on an unhandled exception | The Rack instrumentation |
| Issues with the Ruby backtrace | Unhandled exceptions, recorded on the request span |
| Logs, linked to the trace that produced them | opentelemetry-instrumentation-logger bridges every Logger |
| Child Spans for database and outgoing HTTP calls | The instrumentations for ActiveRecord, pg, mysql2, Redis, Net::HTTP, Faraday and others in instrumentation-all |
Set APP_ENV=production when you check exceptions. In Sinatra's development mode the error page takes over, and the request span for a failed request has the exception but no status code.
Logs
Every Logger in the process is bridged, including the ones your libraries create. One detail decides how the lines read in Traceway:
The log body is the formatted line. With Ruby's default formatter the body is
I, [2026-01-15T10:30:00 #4242] INFO -- : looking up user 101. Severity and time are already separate fields on the record, so give the logger a formatter that prints the message only, asapp.rbdoes.
The SDK's own messages go through the same bridge. Set OTEL_LOG_LEVEL=warn if you do not want its startup line in Logs.
Background Tasks
A job appears under Tasks when its span has kind consumer. A root span with the default kind is dropped.
TRACER.in_span("cleanup-expired-sessions", kind: :consumer) do
cleanup
endThe span name is the task name, so keep it stable and put job ids and batch sizes in attributes. The Context.with_current(OpenTelemetry::Context::ROOT) wrapper in app.rb is only needed because that example starts the job from inside a request. It gives the job a trace of its own. A rake task or a scheduler has no request to detach from, and needs only the in_span call plus the shutdown from otel.rb.
Custom Metrics
METER = OpenTelemetry.meter_provider.meter("my-ruby-service", version: "1.0.0")
SESSIONS_CLEANED = METER.create_counter("app.sessions_cleaned", unit: "{session}")
SESSIONS_CLEANED.add(7, attributes: { "job" => "cleanup-expired-sessions" })The counter appears in metric discovery as app.sessions_cleaned, with job as a tag you can group by. meter takes the version as a keyword argument, unlike tracer. The positional form raises ArgumentError at boot.
Metrics export every 60 seconds by default. While you are checking the integration, set OTEL_METRIC_EXPORT_INTERVAL=5000, and remove it afterwards.
The Ruby web instrumentation records no http.server.* metrics, so there is nothing to switch off. Do not add a view with the drop aggregation: with the current metrics SDK it makes the whole metrics export fail, your own counters included.
Rails
This guide was checked with Sinatra. For Rails, the instrumentation gems document the following, and it was not run for this page:
opentelemetry-instrumentation-allincludes the Rails instrumentation. Put the contents ofotel.rbinconfig/initializers/opentelemetry.rb.- On Rails 7.1 and newer the request span is named from the matched route, such as
GET /users/:id, and carrieshttp.route. - Active Job and Sidekiq create the
consumerspan for each job themselves, so jobs appear under Tasks without a hand-written span.
Verify It Worked
Start the service, then send a few requests:
curl localhost:8080/users/101
curl localhost:8080/users/102
curl localhost:8080/users/103
curl localhost:8080/boom
curl localhost:8080/run-jobSet the dashboard time picker to the last 15 minutes and check:
- Endpoints. One row
GET /users/:idwith a count of 3, andGET /boomwith status 500. - Issues.
RuntimeError: boom: something went wrongwith its backtrace. - Logs. Three
looking up userlines, each linked to its trace. - Tasks.
cleanup-expired-sessions. - Metrics.
app.sessions_cleanedin metric discovery.
No request spans at all, while the job and the logs arrive? The SDK was configured before the web framework was loaded. Nothing at all? Check the endpoint path.