Honeybadger for Ruby

Build Status Gem Version

This is the notifier gem for integrating apps with the :zap: Honeybadger Exception Notifier for Ruby and Rails.

When an uncaught exception occurs, Honeybadger will POST the relevant data to the Honeybadger server specified in your environment.

Supported Ruby versions

Ruby Interpreter Supported Version
MRI >= 2.1.0
JRuby >= 9.1

Supported web frameworks

Framework Version Native?
Rails >= 3.2 yes
Sinatra >= 1.2.1 yes
Rack >= 1.0 middleware

Rails and Sinatra are supported natively (install/configure the gem and you're done). For vanilla Rack apps, we provide a collection of middleware that must be installed manually.

To use Rails 2.x, you'll need to use an earlier version of the Honeybadger gem. Go to version 1.x of the gem docs.

Integrating with other libraries/frameworks is simple! See the documentation to learn about our public API, and see Contributing to suggest a patch.

Supported job queues

Library Version Native?
Sidekiq any yes
Resque any yes
Delayed Job any yes
Sucker Punch any yes
Shoryuken any yes

Other integrations

Library Version Native? Description
Devise/Warden any yes Exceptions are automatically associated with the current user.
Thor any yes Exceptions in commands are automatically reported.

You can integrate honeybadger into any Ruby script via the Honeybadger.notify method.

Getting Started

Honeybadger works out of the box with all popular Ruby frameworks. Installation is just a matter of including the gem and setting your API key. In this section, we'll cover the basics. More advanced installations are covered later.

1. Install the gem

The first step is to add the honeybadger gem to your Gemfile:

gem 'honeybadger'

Tell bundler to install:

$ bundle install

2. Set your API key

Next, you'll set the API key for this project.

$ bundle exec honeybadger install [YOUR API KEY HERE]

This will generate a config/honeybadger.yml file. If you don't like config files, you can place your API key in the $HONEYBADGER_API_KEY environment variable.

Heroku installation

If your app is deployed to heroku, you can configure Honeybadger on your dynos like so:

$ bundle exec honeybadger heroku install [YOUR API KEY HERE]

This will automatically add a HONEYBADGER_API_KEY environment variable to your remote Heroku config and configure deploy notifications.

This step isn't necessary if you're using our Heroku add-on.

3. Set up your code

Rails

You're done! Any rake tasks and job queues that load the Rails environment are also covered.

For more info, check out our screencast on getting up and running with Honeybadger and Rails:

Using the Honeybadger gem with Rails

Sinatra

All you need to do is to include the honeybadger gem:

# Always require Sinatra first.
require 'sinatra'
# Then require honeybadger.
require 'honeybadger'
# Define your application code *after* Sinatra *and* honeybadger:
get '/' do
  raise "Sinatra has left the building"
end

To see an example of a sinatra implementation, check out this video:

Using the Honeybadger gem with Sinatra

Rack

With rack, you have to do things manually, but it's still just a few lines of code:

require 'rack'

# Load the gem
require 'honeybadger'

# Write your app
app = Rack::Builder.app do
  run lambda { |env| raise "Rack down" }
end

# Use Honeybadger's rack middleware
use Honeybadger::Rack::ErrorNotifier

run app

Plain Ruby

To use Honeybadger without any of the automatic integrations, require honeybadger/ruby instead of require 'honeybadger':

require 'honeybadger/ruby'

begin
  # Failing code
rescue => exception
  Honeybadger.notify(exception)
end

All of the public API methods are still available, but none of the plugins, framework integrations, or hooks are run. You will need to manually set up your own middleware and hooks for error monitoring in whatever frameworks you use.

Configuration

There are a few ways to configure the Honeybadger gem. You can use a YAML config file. You can use environment variables. You can use Ruby. Or you can use a combination of the three.

We put together a short video highligting a few of the most common configuration options:

Advanced Honeybadger Gem Usage

YAML Configuration File

By default, Honeybadger looks for a honeybadger.yml configuration file in the root of your project, and then config/honeybadger.yml (in that order).

Here's what the simplest config file looks like:

---
api_key: "my_api_key"

Nested Options

Some configuration options are written in YAML as nested hashes. For example, here's what the logging.path and request.filter_keys options look like in YAML:

---
logging:
  path: "/path/to/honeybadger.log"
request:
  filter_keys:
    - "credit_card"

Environments

Environment-specific options can be set by name-spacing the options beneath the environment name. For example:

---
api_key: "my_api_key"
production:
  logging:
    path: "/path/to/honeybadger.log"
    level: "WARN"

ERB and Regex

The configuration file is rendered using ERB. That means you can set configuration options programmatically. You can also include regular expressions. Here's what that looks like:

---
api_key: "<%= MyApplication.config.api_key %>"
request:
  filter_keys:
    - !ruby/regexp '/credit_card/i'

Configuring with Environment Variables (12-factor style)

All configuration options can also be read from environment variables (ENV). To do this, uppercase the option name, replace all non-alphanumeric characters with underscores, and prefix with HONEYBADGER_. For example, logging.path becomes HONEYBADGER_LOGGING_PATH:

export HONEYBADGER_LOGGING_PATH=/path/to/honeybadger.log

ENV options override other options read from framework or honeybadger.yml sources, so both can be used together.

Configuration via Ruby (programmatic)

To configure Honeybadger from Ruby, use Honeybadger.configure:

Honeybadger.configure do |config|
  config.api_key = 'project api key'
  config.exceptions.ignore += [CustomError]
end

Configuration Options

You can use any of the options below in your config file, or in the environment.

Option Type Description
api_key String The API key for your Honeybadger project.
Default: nil
env String The environment the app is running in. In Rails this defaults to Rails.env.
Default: nil
report_data Boolean Enable/disable reporting of data. Defaults to false for "test", "development", and "cucumber" environments.
Default: true
root String The project's absolute root path.
Default: Dir.pwd
revision String The project's git revision.
Default: revision detected from git
hostname String The hostname of the current box.
Default: Socket.gethostname
backend String An alternate backend to use for reporting data.
Default: nil
debug Boolean Enables verbose debug logging.
Default: false
send_data_at_exit Boolean Finish sending enqueued exceptions before allowing program to exit.
Default: true
disabled Boolean Prevents Honeybadger from starting entirely.
Default: false
config_path String The path of the honeybadger config file. Can only be set via the $HONEYBADGER_CONFIG_PATH environment variable
development_environments Array Environments which will not report data by default (use report_data to enable/disable explicitly).
Default: ["development", "test", "cucumber"]
plugins Array An optional list of plugins to load. Default is to load all plugins.
Default: []
skipped_plugins Array An optional list of plugins to skip.
Default: []
 
LOGGING
logging.path String The path (absolute, or relative from config.root) to the log file. Defaults to the rails logger or STDOUT. To log to standard out, use 'STDOUT'.
Default: nil
logging.level String The log level. Does nothing unless logging.path is also set.
Default: INFO
 
HTTP CONNECTION
connection.secure Boolean Use SSL when sending data.
Default: true
connection.host String The host to use when sending data.
Default: api.honeybadger.io
connection.port Integer The port to use when sending data.
Default: 443
connection.http_open_timeout Integer The HTTP open timeout when connecting to the server.
Default: 2
connection.http_read_timeout Integer The HTTP read timeout when connecting to the server.
Default: 5
connection.proxy_host String The proxy host to use when sending data.
Default: nil
connection.proxy_port Integer The proxy port to use when sending data.
Default: nil
connection.proxy_user String The proxy user to use when sending data.
Default: nil
connection.proxy_pass String The proxy password to use when sending data.
Default: nil
 
REQUEST DATA FILTERING
request.filter_keys Array  A list of keys to filter when sending request data. In Rails, this also includes existing params filters.
Default: ['password', 'password_confirmation']
request.disable_session Boolean Prevent session from being sent with request data.
Default: false
request.disable_params Boolean Prevent params from being sent with request data.
Default: false
request.disable_environment Boolean Prevent Rack environment from being sent with request data.
Default: false
request.disable_url Boolean Prevent url from being sent with request data (Rack environment may still contain it in some cases).
Default: false
 
USER INFORMER
user_informer.enabled Boolean Enable the UserInformer middleware. The user informer displays information about a Honeybadger error to your end-users when you display a 500 error page. This typically includes the error id which can be used to reference the error inside your Honeybadger account.  Learn More
Default: true
user_informer.info String Replacement string for HTML comment in templates.
Default: 'Honeybadger Error {{error_id}}'
 
USER FEEDBACK
feedback.enabled Boolean Enable the UserFeedback middleware. Feedback displays a comment form to your-end user when they encounter an error. When the user creates a comment, it is added to the error in Honeybadger, and a notification is sent.  Learn More
Default: true
 
EXCEPTION REPORTING
exceptions.ignore Array A list of exception class names to ignore (appends to defaults).
Default: ['ActionController::RoutingError', 'AbstractController::ActionNotFound', 'ActionController::MethodNotAllowed', 'ActionController::UnknownHttpMethod', 'ActionController::NotImplemented', 'ActionController::UnknownFormat', 'ActionController::InvalidAuthenticityToken', 'ActionController::InvalidCrossOriginRequest', 'ActionDispatch::ParamsParser::ParseError', 'ActionController::BadRequest', 'ActionController::ParameterMissing', 'ActiveRecord::RecordNotFound', 'ActionController::UnknownAction', 'CGI::Session::CookieStore::TamperedWithCookie', 'Mongoid::Errors::DocumentNotFound', 'Sinatra::NotFound']
exceptions.ignore_only Array A list of exception class names to ignore (overrides defaults).
Default: []
exceptions. ignored_user_agents Array A list of user agents to ignore.
Default: []
exceptions.rescue_rake Boolean Enable rescuing exceptions in rake tasks.
Default: true when run in background; false when run in terminal.
exceptions.notify_at_exit Boolean Report unhandled exception when Ruby crashes (at_exit).
Default: true.
exceptions.source_radius Integer The number of lines before and after the source when reporting snippets.
Default: 2
exceptions.local_variables Boolean Enable sending local variables. Requires the binding_of_caller gem.
Default: false
exceptions.unwrap Boolean Reports #original_exception or #cause one level up from rescued exception when available.
Default: false
 
SIDEKIQ
sidekiq.attempt_threshold Integer The number of attempts before notifications will be sent.
Default: 0
sidekiq.use_component Boolean Automatically set the component to the class of the job. Helps with grouping.
Default: true
DELAYED JOB
delayed_job.attempt_threshold Integer The number of attempts before notifications will be sent.
Default: 0
SHORYUKEN
shoryuken.attempt_threshold Integer The number of attempts before notifications will be sent.
Default: 0
SINATRA
sinatra.enabled Boolean Enable Sinatra auto-initialization.
Default: true

Public Methods

What follows is a summary of the gem's most commonly-used public methods. For a more authoritative list, read the full API documentation.

Honeybadger.context(): Set metadata to be sent if an exception occurs

Sometimes, default exception data just isn't enough. If you have extra data that will help you in debugging, send it as part of an error's context. View full method documentation

Global context is stored in a thread local variable and automatically reported with any exception which occurs within the current thread's execution.

Use this method if:

  • You want to record the current user's id at the time of an exception
  • You need to send raw POST data for use in debugging
  • You have any other metadata you'd like to send with an exception

Examples:

Honeybadger.context({my_data: 'my value'})

# Inside a Rails controller:
before_action do
  Honeybadger.context({user_id: current_user.id})
end

# Clearing global context:
Honeybadger.context.clear!

# Fetching current context
Honeybadger.get_context

Honeybadger.notify(): Send an exception to Honeybadger.

You normally won't have to use this method. Honeybadger detects and reports errors automatically in Rails and other popular frameworks. But there may be times when you need to manually control exception reporting. View full method documentation

Use this method if:

  • You've rescued an exception, but still want to report it
  • You need to report an exception outside of a supported framework.
  • You want complete control over what exception data is sent to us.

Examples:

# Sending an exception that you've already rescued
begin
  fail 'oops'
rescue => exception
  Honeybadger.notify(exception)
end

Honeybadger.configure(): Configure Honeybadger from Ruby

This method allows you to configure Honeybadger at runtime.

Use this method if:

  • You want to change Honeybadger's configuration from inside Ruby rather than (or in addition to) using the honeybadger.yml file or environment variables.

Examples:

Honeybadger.configure do |config|
  config.api_key = 'project api key'
  config.exceptions.ignore += [CustomError]
end

Honeybadger.exception_filter(): Programmatically ignore exceptions

This method lets you add a callback that will be run every time an exception is about to be reported to Honeybadger. If your callback returns a truthy value, the exception won't be reported. View full method documentation

Use this method if:

  • You need to ignore exceptions that meet complex criteria
  • The built-in configuration options for filtering based on exception class and user agent aren't enough

Examples:

# Here's how you might ignore exceptions based on their error message:
Honeybadger.exception_filter do |notice|
  notice[:error_message] =~ /sensitive data/
end

You can access any attribute on the notice argument by using the [] syntax. For a full list of attributes, see the documentation for Notice Here are a few examples to get you started:

Honeybadger.exception_filter do |notice|
  notice[:exception].class < MyError &&
  notice[:params][:name] =~ "bob" &&
  notice[:context][:current_user_id] != 1
end

WARNING: While it is possible to use this callback to modify the data that is reported to Honeybadger, this is not officially supported and may not be allowed in future versions of the gem.


Honeybadger.exception_fingerprint(): Customize your error grouping.

This method lets you add a callback that should return a unique string given a Honeybadger::Notice instance. All notices which match the same string will be grouped together in Honeybadger.

Use this method if:

  • You currently receive too many error notifications
  • You want to group some errors together which are currently unique
  • You don't want to group some errors which are currently grouped

Examples:

Honeybadger.exception_fingerprint do |notice|
  [notice[:error_class], notice[:component], notice[:backtrace].to_s].join(':')
end

Honeybadger.backtrace_filter(): Filter your backtrace.

This method allows you to add a callback which modifies each line of the backtrace before a notification happens.

Use this method if:

  • You want to change or sanitize common data in your exception backtraces

Examples:

Honeybadger.backtrace_filter do |line|
  line.gsub(/^\/my\/unknown\/bundle\/path/, "[GEM_ROOT]")
end

Deployment Tracking

Honeybadger has an API to keep track of project deployments. Whenever you deploy, all errors for that environment will be resolved automatically. You can choose to enable or disable the auto-resolve feature from your Honeybadger project settings page.

Capistrano Deployment Tracking

In order to track deployments using Capistrano, simply require Honeybadger's Capistrano task in your Capfile file:

require "capistrano/honeybadger"

If you ran the honeybadger install command in a project that was previously configured with Capistrano, we already added this for you.

Adding options to your  config/deploy.rb file allows you to customize how the deploy task is executed. The syntax for setting them looks like this:

set :honeybadger_env, "preprod"

You can use any of the following options when configuring capistrano.

Option
honeybadger_user Honeybadger will report the name of the local user who is deploying (using whoami or equivalent). Use this option to to report a different user.
honeybadger_env Honeybadger reports the environment supplied by capistrano by default. Use this option to change the reported environment.
honeybadger_api_key Honeybadger uses your configured API key by default. Use this option to override.
honeybadger_async_notify Run deploy notification task asynchronously using nohup. True or False. Defaults to false.
honeybadger_server The api endpoint that receives the deployment notification.
honeybadger The name of the honeybadger executable. Default: "honeybadger"

Heroku Deployment Tracking

Deploy tracking via Heroku is implemented using Heroku's free deploy hooks addon. To install the addon and configure it for Honeybadger, run the following CLI command from your project root:

$ bundle exec honeybadger heroku install_deploy_notification

If the honeybadger CLI command fails for whatever reason, you can add the deploy hook manually by running:

$ heroku addons:add deployhooks:http --url="https://api.honeybadger.io/v1/deploys?deploy[environment]=production&deploy[local_username]={{user}}&deploy[revision]={{head}}&api_key=asdf" --app app-name

You should replace the api key and app-name with your own values. You may also want to change the environment (set to production by default).

Deployment Tracking Via command line

We provide a CLI command to send deployment notifications manually:

bundle exec honeybadger deploy --environment=production

Run  bundle exec honeybadger help deploy for all available options.

Honeybadger CLI

The Honeybadger CLI provides a Command Line Interface for various Honeybadger-related programs and utilities. All features are available through the honeybadger command and can be used independently of Bundler/Rails.

When using the honeybadger gem with Bundler, run bundle exec honeybadger.

To use outside of bundler, install the Honeybadger gem with gem install honeybadger and then run honeybadger.

CLI Configuration

The honeybadger command optionally reads configuration from the following locations. Each location in the list takes precedence over the previous location:

  1. ~/honeybadger.yml
  2. ./config/honeybadger.yml
  3. ./honeybadger.yml
  4. Rails/Ruby configuration (only when called from a Rails app root)
  5. Environment variables
  6. Command-line flags (i.e. --api-key)

The following configuration options are used by the CLI when applicable: api_key, env. See Configuration Options

All other options must be passed as command-line flags.

CLI Commands

The following commands are available through the honeybadger CLI:

Command Description
honeybadger deploy Notify Honeybadger of deployment
honeybadger exec Execute a command. If the exit status is not 0, report the result to Honeybadger
honeybadger help Describe available commands or one specific command
honeybadger heroku Manage Honeybadger on Heroku
honeybadger install Install Honeybadger into a new project
honeybadger notify Notify Honeybadger of an error
honeybadger test Send a test notification from Honeybadger

For additional info about each command, run honeybadger help.

Rails initialization

When run from the root of a Rails project, the honeybadger command will load the Rails environment so that any framework/programmatic configuration is picked up.

Cron/command line monitoring

honeybadger exec can be used from the command line/terminal to monitor failed commands. To use it, prefix any normal command with honeybadger exec (much like bundle exec):

$ honeybadger exec my-command --my-flag

If the command executes successfully, honeybadger exits with code 0. It prints any output from the command by default. To use with cron's automatic email feature, use the --quiet flag, which will suppress all standard output from the origin command unless the command fails and the Honeybadger notification fails, in which case it will dump the output so that cron can send a backup email notification.

For full usage run honeybadger help exec.

Notify from the command line

To send a Honeybadger notification from the command line/terminal, use honeybadger notify:

$ honeybadger notify --message "This is an error from the command line"

For full usage run honeybadger help notify.

Reporting to multiple Honeybadger projects in the same app

To send errors to another Honeybadger project, configure an additional agent:

OtherBadger = Honeybadger::Agent.new

OtherBadger.configure do |config|
  config.api_key = 'project api key'
end

begin
  # Failing code
rescue => exception
  OtherBadger.notify(exception)
end

Agents do not use the global honeybadger.yml or environment variable configuration and must be configured manually after they are instantiated.

Custom Error Pages

The Honeybadger gem has a few special tags that it looks for whenever you render an error page. These can be used to display extra information about the error, or to ask the user for information about how they triggered the error.

Displaying Error ID

When an error is sent to Honeybadger, our API returns a unique UUID for the occurrence within your project. This UUID can be automatically displayed for reference on Rails error pages (e.g. public/500.html) or any rack output by including the Honeybadger::UserInformer middleware.

To include the error id, simply place this magic HTML comment on your error page:

<!-- HONEYBADGER ERROR -->

By default, we will replace this tag with:

Honeybadger Error {{error_id}}

Where {{error_id}} is the UUID. You can customize this output by overriding the user_informer.info option in your honeybadger.yml file (you can also enabled/disable the middleware):

user_informer:
  enabled: true
  info: "Error ID: {{error_id}}"

You can use that UUID to load the error at the site by going to  https://www.honeybadger.io/notice/UUID.

Collecting User Feedback

When an error is sent to Honeybadger, an HTML form can be generated so users can fill out relevant information that led up to that error. Feedback responses are displayed inline in the comments section on the fault detail page.

To include a user feedback form on your error page, simply add this magic HTML comment:

<!-- HONEYBADGER FEEDBACK -->

You can change the text displayed in the form via the Rails internationalization system. Here's an example:

# config/locales/en.yml
en:
  honeybadger:
    feedback:
      heading: "Care to help us fix this?"
      explanation: "Any information you can provide will help us fix the problem."
      submit: "Send"
      thanks: "Thanks for the feedback!"
      labels:
        name: "Your name"
        email: "Your email address"
        comment: "Comment (required)"

Testing Honeybadger in your integration tests

It is possible to test Honeybadger's integration with your application using the included test backend.

The test backend replaces the default server backend with a stub that records error notices rather than sending them, allowing all but the HTTP notification itself to be verified. Alternatively, you could use something like WebMock to perform a similar test using the "server" backend.

Configuring the test backend

To use the test backend, set the backend configuration option to "test" in honeybadger.yml for your test environment only:

api_key: 'project api key'
test:
  backend: test

You can also use the HONEYBADGER_BACKEND environment variable to configure the test backend. Note that you must also configure your API key for the test to succeed.

Writing the integration test

The test backend can be used in any testing framework to test any code which reports an error with Honeybadger.notify. A common scenario is to test the Rails-integration which reports exceptions in a Rails controller automatically.

The following example uses RSpec to test error notification in a Rails controller.

First, create the controller:

# app/controllers/honeybadger_test_controller.rb
class HoneybadgerTestController < ApplicationController
  ERROR = RuntimeError.new("testing reporting an error to Honeybadger")

  def index
    raise ERROR
  end
end

Next, create a route. For security, it's a good idea to enable the route only in the test environment:

  # config/routes.rb

  # ...
  get '/test/honeybadger' => 'honeybadger_test#index' if Rails.env.test?

Finally, create the integration test:

# spec/features/honeybadger_spec.rb
require 'rails_helper'

describe "error notification" do
  it "notifies Honeybadger" do
    expect {
      # Code to test goes here:
      expect { visit '/test/honeybadger' }.to raise_error(HoneybadgerTestController::ERROR)

      # Important: `Honeybadger.flush` ensures that asynchronous notifications
      # are delivered before the test's remaining expectations are verified.
      Honeybadger.flush
    }.to change(Honeybadger::Backend::Test.notifications[:notices], :size).by(1)
    expect(Honeybadger::Backend::Test.notifications[:notices].first.error_message).to eq('testing reporting an error to Honeybadger')
  end
end

Troubleshooting

See TROUBLESHOOTING.md

Changelog

See https://github.com/honeybadger-io/honeybadger-ruby/blob/master/CHANGELOG.md

Development

Pull requests are welcome. If you're adding a new feature, please submit an issue as a preliminary step; that way you can be (moderately) sure that your pull request will be accepted.

If you're integrating your gem/open source project with Honeybadger, please consider submitting an official plugin to our gem. Submit an issue to discuss with us!

We use TomDoc to document our API. Classes and methods which are safe to depend on in your gems/projects are marked "Public". All other classes/methods are considered internal and may change without notice -- don't depend on them! If you need a new public API, we're happy to work with you. Submit an issue to discuss.

To contribute your code:

  1. Fork it.
  2. Create a topic branch git checkout -b my_branch
  3. Make your changes and add an entry to the CHANGELOG.
  4. Commit your changes git commit -am "Boom"
  5. Push to your branch git push origin my_branch
  6. Send a pull request

Running the tests

We're using the Appraisal gem to run our RSpec test suite against multiple versions of Rails.

  • The unit test suite can be run with rake spec:units.
  • The integration test suite can be run with rake spec:features.
  • The combined suite can be run with rake.

License

The Honeybadger gem is MIT licensed. See the LICENSE file in this repository for details.