JustAnalytics for Ruby on Rails

Step-by-step guide to add analytics, error tracking, and APM to your Rails app

JustAnalytics for Ruby on Rails

Add distributed tracing, error tracking, structured logging, and infrastructure metrics to your Rails application.

Time to data: 3-5 minutes

Prerequisites#


Install the gem

Add to your Gemfile:

gem "justanalytics"

Then install:

bundle install

Create an initializer

The SDK auto-configures Rails middleware via a Railtie. Just initialize it:

# config/initializers/justanalytics.rb
JustAnalytics.init(
  site_id: ENV["JA_SITE_ID"],
  api_key: ENV["JA_API_KEY"],
  service_name: "rails-api",
  environment: Rails.env,
  release: ENV.fetch("APP_VERSION", "0.0.0"),
)

Add credentials to your environment. For Rails credentials:

rails credentials:edit
# config/credentials.yml.enc
justanalytics:
  site_id: site_abc123
  api_key: ja_sk_your_api_key_here

Then reference them in the initializer:

JustAnalytics.init(
  site_id: Rails.application.credentials.dig(:justanalytics, :site_id),
  api_key: Rails.application.credentials.dig(:justanalytics, :api_key),
  service_name: "rails-api",
  environment: Rails.env,
)

Or use environment variables (.env with dotenv or your deployment platform):

JA_SITE_ID=site_abc123
JA_API_KEY=ja_sk_your_api_key_here

Automatic request tracing

The Railtie middleware automatically traces all incoming HTTP requests. No changes needed in your controllers:

# app/controllers/users_controller.rb
class UsersController < ApplicationController
  # Automatically traced as "GET /users/:id"
  def show
    @user = User.find(params[:id])
    render json: @user
  end

  # Automatically traced as "POST /users"
  def create
    @user = User.create!(user_params)
    render json: @user, status: :created
  end
end

Add error tracking

Unhandled exceptions are captured automatically. For manual error reporting:

# app/controllers/application_controller.rb
class ApplicationController < ActionController::API
  rescue_from StandardError do |exception|
    JustAnalytics.capture_exception(exception, tags: {
      controller: self.class.name,
      action: action_name,
    })
    render json: { error: "Internal server error" }, status: :internal_server_error
  end
end

Add client-side tracking (optional)

For frontend analytics, add the scripts to your layout:

<!-- app/views/layouts/application.html.erb -->
<head>
  <script defer data-site-id="<%= ENV['JA_SITE_ID'] %>"
          src="https://justanalytics.app/tracker.js"></script>
  <script defer data-site-id="<%= ENV['JA_SITE_ID'] %>"
          src="https://justanalytics.app/monitor.js"></script>
</head>

Verify Your Setup

Visit any page or send an API request, then check the Traces tab. You should see Rails controller action spans.

Open Dashboard

Advanced Features#

Custom spans#

class OrdersController < ApplicationController
  def create
    JustAnalytics.start_span("create-order", op: "controller") do |span|
      span.set_attribute("order.items", params[:items].length)

      @order = JustAnalytics.start_span("db.create", op: "db") do
        Order.create!(order_params)
      end

      JustAnalytics.start_span("send-confirmation", op: "task") do
        OrderMailer.confirmation(@order).deliver_later
      end

      render json: @order, status: :created
    end
  end
end

User identification#

# app/controllers/application_controller.rb
before_action :identify_user

private

def identify_user
  return unless current_user
  JustAnalytics.set_user(
    id: current_user.id.to_s,
    email: current_user.email,
  )
end

Structured logging#

JustAnalytics.logger.info("User signed up", user_id: "u123", plan: "pro")
JustAnalytics.logger.error("Payment failed", order_id: "o456", reason: "declined")
JustAnalytics.logger.warn("Rate limit approaching", ip: request.remote_ip)

Sidekiq integration#

# config/initializers/sidekiq.rb
Sidekiq.configure_server do |config|
  config.server_middleware do |chain|
    chain.add JustAnalytics::SidekiqServerMiddleware
  end
end

Sidekiq.configure_client do |config|
  config.client_middleware do |chain|
    chain.add JustAnalytics::SidekiqClientMiddleware
  end
end

Net::HTTP auto-instrumentation#

Automatically trace outgoing HTTP requests:

# config/initializers/justanalytics.rb (add after init)
JustAnalytics::NetHttpPatch.enable!

# Now all Net::HTTP calls are traced
uri = URI("https://api.stripe.com/v1/charges")
response = Net::HTTP.get_response(uri)

Custom metrics#

JustAnalytics.record_metric("custom.queue_size", Sidekiq::Queue.new.size)
JustAnalytics.record_metric("custom.cache_hit_rate", cache_stats[:hit_rate])

Environment variables#

| Variable | Description | Required | |----------|-------------|----------| | JA_SITE_ID | Your site ID from the dashboard | Yes | | JA_API_KEY | API key (starts with ja_sk_) | Yes | | APP_VERSION | Release version for tracking | No |