Skip to content
Last9 Last9

Ruby on Rails

Send distributed traces to Last9 from a Ruby on Rails app using OpenTelemetry

Ruby on Rails is a server-side web application framework written in Ruby. This comprehensive guide will help you instrument your Ruby on Rails application with OpenTelemetry and smoothly send the traces to a Last9 cluster. You can also check out the example application on GitHub↗.

Pre-requisites#Copy link

  1. You have a Ruby on Rails application.
  2. You have signed up for Last9, created a cluster, and obtained the following OTLP credentials from the Integrations page:
    • endpoint
    • auth_header

Install OpenTelemetry packages#Copy link

To install the required packages, add the following lines to your Gemfile:

gem 'opentelemetry-sdk'
gem 'opentelemetry-exporter-otlp'
gem 'opentelemetry-instrumentation-all'
gem 'dotenv-rails', groups: [:development, :test]

Then, run the following command to install the packages:

Terminal window
bundle install

Set the environment variables#Copy link

Create a .env file in the root directory of your application and add the following environment variables:

Terminal window
OTEL_SERVICE_NAME=ruby-on-rails-api-service
OTEL_EXPORTER_OTLP_ENDPOINT=<ENDPOINT>
OTEL_EXPORTER_OTLP_HEADERS="Authorization=Basic <BASIC_AUTH_HEADER>"
OTEL_TRACES_EXPORTER=otlp

Note: Replace <BASIC_AUTH_HEADER> with the URL encoded value of the basic auth header.

Instrument your application#Copy link

In config/initializers/opentelemetry.rb, add the following code to instrument your application:

require 'opentelemetry/sdk'
require 'opentelemetry/exporter/otlp'
require 'opentelemetry/instrumentation/all'
# Exporter and Processor configuration
otel_exporter = OpenTelemetry::Exporter::OTLP::Exporter.new
processor = OpenTelemetry::SDK::Trace::Export::BatchSpanProcessor.new(otel_exporter)
OpenTelemetry::SDK.configure do |c|
# Exporter and Processor configuration
c.add_span_processor(processor) # Created above this SDK.configure block
# Resource configuration
c.resource = OpenTelemetry::SDK::Resources::Resource.create({
OpenTelemetry::SemanticConventions::Resource::SERVICE_NAME => 'ruby-on-rails-api-service',
OpenTelemetry::SemanticConventions::Resource::SERVICE_VERSION => "0.0.0",
OpenTelemetry::SemanticConventions::Resource::DEPLOYMENT_ENVIRONMENT => Rails.env.to_s
})
c.use_all() # enables all instrumentation!
end

This code snippet configures the OpenTelemetry SDK to use the OTLP exporter and enables instrumentation for all standard components of a Rails application.

Run the application#Copy link

Start your Ruby on Rails application by running the following command:

Terminal window
bin/rails server

Visualize data#Copy link

After running the Ruby on Rails app, you can visualize the traces in the Last9’s APM dashboard.

image


Troubleshooting#Copy link

Please get in touch with us on Discord or Email if you have any questions.