Skip to main content

Sinatra

Send traces to Levitate from a Sinatra app using OpenTelemetry

Introduction

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

Pre-requisites

  1. You've a Sinatra application.
  2. You have signed up for Levitate, 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:

# Gemfile
source 'https://rubygems.org'

gem 'sinatra'

gem 'dotenv'
gem 'opentelemetry-sdk'
gem 'opentelemetry-exporter-otlp'
gem 'opentelemetry-instrumentation-all'

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=sinatra-api-service
OTEL_EXPORTER_OTLP_ENDPOINT=https://otlp.last9.io
OTEL_EXPORTER_OTLP_HEADERS="Authorization=<BASIC_AUTH_HEADER>"
OTEL_TRACES_EXPORTER=otlp

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

In app.rb, add the following code to load the environment variables:

# app.rb
require 'dotenv/load'
# Rest of the code...
note

You can also other mechanisms to load environment variables and configuration such as loading a YAML file.

Instrument your application

Create a new file instrumentation.rb and add the following code:

require 'opentelemetry/sdk'
require 'opentelemetry/exporter/otlp'
require 'opentelemetry/instrumentation/all'

OpenTelemetry::SDK.configure do |c|
c.service_name = 'sinatra-api-service'
c.use_all() # enables all instrumentation!
end

This code snippet configures the OpenTelemetry SDK to use the OTLP exporter and enables all instrumentation. We will require this file in app.rb to instrument the application.

In app.rb, require the instrumentation.rb file:

# app.rb

require_relative 'instrumentation'

# Rest of the code...

Run the application

Run the Sinatra application using the following command:

ruby app.rb

Visualize the traces

After running the Sinatra app, you can visualize the traces in the Levitate's APM dashboard.

image

Troubleshooting

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