Ruby on Rails
Send distributed traces to Last9 from a Ruby on Rails app using OpenTelemetry
Introduction
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
- You have a Ruby on Rails application.
- 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
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:
bundle install
Set the environment variables
Create a .env
file in the root directory of your application and add the following environment variables:
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
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
Start your Ruby on Rails application by running the following command:
bin/rails server
Visualize data
After running the Ruby on Rails app, you can visualize the traces in the Last9's APM dashboard.
Troubleshooting
Please get in touch with us on Discord or Email if you have any questions.