ruby reference: Documentation for the Honeybadger Ruby client library (SDK) and platform. # Honeybadger for Ruby > Ruby exception tracking with the honeybadger Ruby gem. Hi there! You’ve found Honeybadger’s docs on **Ruby exception tracking**. In this guide we’re going to discuss the **honeybadger Ruby gem** and how to use it to track exceptions in your Ruby applications. If you’re new to Honeybadger, we recommend taking a moment to read through. This guide is also your reference for how to use the gem in the future, so **bookmark it**. For a refresher on working with exceptions in Ruby, check out the [Honeybadger guide to Ruby exceptions](https://www.exceptionalcreatures.com/guides/what-are-ruby-exceptions.html). ## Getting started [Section titled “Getting started”](#getting-started) Getting started is easy! First, see our [installation and configuration guide](/lib/ruby/getting-started/introduction/) for instructions on adding Honeybadger to your app in less than 3 minutes. Next steps: * Learn about getting the most out of Honeybadger for your platform or framework with one of our **Integration guides**: [Rails](/lib/ruby/integration-guides/rails-exception-tracking/), [Sinatra](/lib/ruby/integration-guides/sinatra-exception-tracking/), [Rack](/lib/ruby/integration-guides/rack-exception-tracking/), [Heroku](/lib/ruby/integration-guides/heroku-exception-tracking/), [AWS Lambda](/lib/ruby/integration-guides/aws-lambda-exception-tracking/), or [other Ruby apps](/lib/ruby/integration-guides/ruby-exception-tracking/). * See the **Gem Reference section** for details about the [gem’s configuration](/lib/ruby/gem-reference/configuration/), [public method API](https://www.rubydoc.info/gems/honeybadger), and [CLI](/lib/ruby/gem-reference/cli/) (Command Line Interface). * Finally, you may also be interested in **other areas of our documentation**, such as our [REST API guide](/api/) or [general product guides](/). ## Getting support [Section titled “Getting support”](#getting-support) If you’re having trouble working with the gem (such as you aren’t receiving error reports when you should be): 1. Read [Frequently asked questions](/lib/ruby/support/faq/) 2. Upgrade to the latest gem version if possible (you can find a list of bugfixes and other changes in the [CHANGELOG](https://github.com/honeybadger-io/honeybadger-ruby/blob/master/CHANGELOG.md)) 3. Run through our [Troubleshooting guide](/lib/ruby/support/troubleshooting/) For all other problems, contact support for help: **If your issue is gem-related**, here are a few items you can send us which will make it easier to spot the problem: * Run `bundle exec honeybadger test --file=honeybadger_test.txt` from the server having the problem and attach the generated honeybadger\_test.txt file * Run `bundle exec rake middleware` from the server having the problem and attach the output as plaintext * Attach your config/honeybadger.yml file * Attach your Gemfile.lock file # Adding context to errors > Add context to Ruby error reports with custom data to improve debugging and error resolution. 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. Context is what you’re looking for if: * You want to record the current user’s id or email address 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 Honeybadger supports two types of context: global and local. ## Global context [Section titled “Global context”](#global-context) Global context is automatically reported with any exception which occurs after the context has been created: ```ruby Honeybadger.context({ my_data: 'my value' }) ``` A few other methods are also available when working with context: ```ruby # Clear the global context: Honeybadger.context.clear! # Fetch the global context: Honeybadger.get_context ``` Global context is stored in a [thread-local variable](https://ruby-doc.org/core-3.0.1/Thread.html#class-Thread-label-Thread+variables+and+scope), which means each thread has its own global context. ## Local context [Section titled “Local context”](#local-context) Local context is similar to global context but it is only reported with exceptions that occur within a specific block of code where the local context is set. This is useful when you want to add context data for a specific operation or a set of operations, but you don’t want that context to leak into other parts of your application. You can set local context by passing a block to the `Honeybadger.context` method: ```ruby Honeybadger.context({ local_data: 'local value' }) do # This block of code has access to the local context. # If an exception occurs here, the local context will be reported with the exception. end ``` The local context is automatically cleared after the block is executed, even if an exception is raised within the block. This ensures that the local context does not leak into other parts of your application. To fetch the local context, you can call `Honeybadger.get_context`: ```ruby # Set global context Honeybadger.context({ global_data: 'global value' }) # Fetch and print global context puts Honeybadger.get_context # Expected output: { global_data: 'global value' } # Set local context within a block Honeybadger.context({ local_data: 'local value' }) do # Fetch and print context within the block puts Honeybadger.get_context # Expected output: { global_data: 'global value', local_data: 'local value' } end # Fetch and print context outside the block puts Honeybadger.get_context # Expected output: { global_data: 'global value' } ``` Calling `Honeybadger.get_context` within a block will return a merged hash of the global and local context. If there are conflicts, the local context will take precedence. Remember, local context is also stored in a thread-local variable, which means each thread has its own local context. ## Context in `Honeybadger.notify` [Section titled “Context in Honeybadger.notify”](#context-in-honeybadgernotify) You can also add context to a manual error report using the `:context` option, like this: ```ruby Honeybadger.notify(exception, context: { my_data: 'my local value' }) ``` Local context always overrides any global values when the error is reported. ## Special context values [Section titled “Special context values”](#special-context-values) While you can add any key/value data to context, a few keys have special meaning in Honeybadger: | Option | Description | | ------------- | -------------------------------------------------------------------------------------------------------- | | `:_action` | This will set the `action` attribute of your error data if not already set. | | `:_component` | This will set the `component` attribute of your error data if not already set. | | `:user_id` | The `String` user ID used by Honeybadger to aggregate user data across occurrences on the error page. | | `:user_email` | Same as `:user_id`, but for email addresses | | `:tags` | A `String` comma-separated list of tags. When present, tags will be applied to errors with this context. | Using the `:_action` and `:_component` keys are useful when you are manually reporting errors via `Honeybadger.notify` or `Rails.error.report`. ## Defining context on objects [Section titled “Defining context on objects”](#defining-context-on-objects) Context must either be a `Hash`, or it must define the method `#to_honeybadger_context` to return a `Hash`. For example, to pass a `User` instance to `Honeybadger.context`: ```ruby class User < ApplicationRecord def to_honeybadger_context { user_id: id, user_email: email } end end user = User.last Honeybadger.context(user) ``` When the `#to_honeybadger_context` method is defined on an `Exception` class, the context will be automatically added when the exception is reported: ```ruby class CustomError < StandardError def to_honeybadger_context { tags: 'custom' } end end raise CustomError, 'This error will be reported with context' ``` ## Limits [Section titled “Limits”](#limits) Honeybadger uses the following limits to ensure the service operates smoothly for everyone: * Nested objects have a max depth of 20 * Context values have a max size of 64Kb When an error notification includes context data that exceed these limits, the context data will be truncated, and the notification will still be processed. # Breadcrumbs > Add breadcrumbs to Ruby error reports to track events and user actions leading up to errors. Breadcrumbs are a useful debugging tool that give you the ability to record contextual data as an event called a `breadcrumb`. When your Project reports an Error (Notice), we send along the breadcrumbs recorded during the execution (request, job, task, etc…). [Context](/lib/ruby/errors/adding-context-to-errors/) is another way to store extra data to help with debugging. Context is still a great way to attach global data to an error, however, there are scenarios where Breadcrumbs might be a better choice: * You want to record metadata that contains duplicate keys * You want to group related data * You care about when an event happened in relation to an error ## Automatic Rails breadcrumbs [Section titled “Automatic Rails breadcrumbs”](#automatic-rails-breadcrumbs) Rails provides a robust [Active Support Instrumentation](https://guides.rubyonrails.org/active_support_instrumentation.html) implementation that allows us to automatically add insights into your errors. The instrumentation breadcrumbs are very configurable. You can modify a copy of the default config if you want to change the default behavior. Here’s how you might remove all ActiveRecord breadcrumb events: ```ruby notifications = Honeybadger::Breadcrumbs::ActiveSupport.default_notifications notifications.delete("sql.active_record") Honeybadger.configure do |config| config.breadcrumbs.active_support_notifications = notifications end ``` ```ruby notifications = Honeybadger::Breadcrumbs::ActiveSupport.default_notifications notifications["sql.active_record"][:select_keys].delete_if {|k| k == :sql} Honeybadger.configure do |config| config.breadcrumbs.active_support_notifications = notifications end ``` You can set an empty hash to remove ActiveSupport notifications all together: ```ruby Honeybadger.configure do |config| config.breadcrumbs.active_support_notifications = {} end ``` The key for each instrumentation hash is the hook id used for subscribing to the ActiveSupport notification. For example ```ruby { "process_action.action_controller" => { message: "Action Controller Action Process", select_keys: [:controller, :action, :format, :method, :path, :status, :view_runtime, :db_runtime], category: "request", } } ``` will subscribe to the `process_action.action_controller` instrumentation notification and produce a breadcrumb with the specified `message` and `category` and restrict [the keys](https://guides.rubyonrails.org/active_support_instrumentation.html#process-action-action-controller) passed into the metadata to the set supplied by `select_keys`. Here are all the options you can pass into an instrumentation hash: | Option name | Description | | | --------------- | ----------------------------------------------------------------------------------------------------------------------------------------- | ------ | | `:message` | A `String` message that describes the event or you can dynamically build the message by passing a `Proc` that accepts the event metadata. | | | `:category` | A `String` key used to group specific types of events | | | `:select_keys` | An (*optional*) `Array` of keys that filters what data we select from the instrumentation data | `Proc` | | `:exclude_when` | A (*optional*) `Proc` that accepts the data payload. A truthy return value will exclude this event from the payload | `Proc` | | `:transform` | A (*optional*) `Proc` that accepts the data payload. The return value will replace the current data hash | | Check out the [config](https://github.com/honeybadger-io/honeybadger-ruby/blob/master/lib/honeybadger/breadcrumbs/active_support.rb). to see what we instrument by default. ## Custom breadcrumbs [Section titled “Custom breadcrumbs”](#custom-breadcrumbs) You can also add your own custom breadcrumb events: ```ruby Honeybadger.add_breadcrumb("Email Sent", metadata: { user: user.id, message: message }) ``` The first argument (`message`) is the only required data. In the UI, `message` is front and center in your breadcrumbs list, so we prefer a more terse description accompanied by rich metadata. Here are the options allowed while adding breadcrumbs: | Option name | Description | | ----------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `:metadata` | A (*optional*) `Hash` that contains any contextual data to help debugging. We only accept a single-level hash with simple primitives as values (Strings, Numbers, Booleans & Symbols) | | `:category` | An (*optional*) `String` key used to group specific types of events. We primarily use this key to display a corresponding icon, however, you can use it for your own categorization if you like | ## Logging breadcrumbs [Section titled “Logging breadcrumbs”](#logging-breadcrumbs) All log messages, by default, sent to the `::Logger` class are converted into breadcrumbs. Breadcrumbs from logging can be disabled within the config: ```yaml --- breadcrumbs: logging: enabled: false ``` ## Categories [Section titled “Categories”](#categories) A Breadcrumb category is a top level property. It’s main purpose is to allow for display differences (icons & styling) in the UI. You may give a breadcrumb any category you wish. Unknown categories will default to the ‘custom’ styling. Here are the current categories and a brief description of how you might categorize certain activity: | Category | Description | | -------- | ------------------------------------------- | | custom | Any other kind of breadcrumb | | error | A thrown error | | query | Access or Updates to any data or file store | | job | Queueing or Working via a job system | | request | Outbound / inbound requests | | render | Any output or serialization via templates | | log | Any messages logged | | notice | A Honeybadger Notice | ## Disabling breadcrumbs [Section titled “Disabling breadcrumbs”](#disabling-breadcrumbs) As of version `4.6.0`, Breadcrumbs are enabled by default. You can disable breadcrumbs via the `breadcrumbs.enabled` configuration option (in YAML): ```yaml --- breadcrumbs: enabled: false ``` or in the Ruby config: ```ruby Honeybadger.configure do |config| config.breadcrumbs.enabled = false end ``` ## Limits [Section titled “Limits”](#limits) Honeybadger uses the following limits to ensure the service operates smoothly for everyone: * We only store & transmit 40 breadcrumb events. The current implementation only keeps the 40 latest breadcrumb events. * Metadata can only hold scalar values (no nested hashes or arrays) * String values have a max size of 64Kb # Collecting user feedback > Collect user feedback when errors occur in Ruby applications to get context directly from affected users. The Honeybadger gem has a few special tags that it looks for whenever you render an error page in a Rack-based application. These can be used to display extra information about the error, or to ask the user for information about how they triggered the error. ## Installing the middleware [Section titled “Installing the middleware”](#installing-the-middleware) Honeybadger installs the middleware automatically in Rails projects. For all other applications, the middleware must be installed manually: ```ruby use Honeybadger::Rack::UserInformer use Honeybadger::Rack::UserFeedback ``` ## Displaying the error ID [Section titled “Displaying the error ID”](#displaying-the-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 error pages. To include the error id, simply place this magic HTML comment on your error page (normally `public/500.html` in Rails): ```html ``` By default, we will replace this tag with: ```plaintext 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): config/honeybadger.yml ```yaml 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://app.honeybadger.io/notice/some-uuid-goes-here](https://app.honeybadger.io/notice/). ## Displaying a feedback form [Section titled “Displaying a feedback form”](#displaying-a-feedback-form) 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 (normally `public/500.html` in Rails): ```html ``` You can change the text displayed in the form via the Rails internationalization system. Here’s an example: config/locales/en.yml ```yaml 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)" ``` The feedback form can be enabled and disabled using the `feedback.enabled` config option (defaults to `true`): config/honeybadger.yml ```yaml feedback: enabled: true ``` # Customizing error grouping > Customize how errors are grouped in Ruby applications to better organize and prioritize error reports. Honeybadger groups similar exceptions together using rules which we’ve found to work the best in most cases. The default information we use to group errors is: 1. The file name, method name, and line number of the error’s location 2. The class name of the error 3. The component/controller name We use this information to construct a “fingerprint” of the exception. Exceptions with the same fingerprint are treated as the same error in Honeybadger. You can customize the grouping for each exception by changing the error class name, component, or stack trace—or by sending a custom fingerprint. There are two ways you can customize the fingerprint: globally (for all exceptions that are reported from your app), and locally (when calling `Honeybadger.notify`). ## Customizing the grouping for all exceptions [Section titled “Customizing the grouping for all exceptions”](#customizing-the-grouping-for-all-exceptions) The `Honeybadger.before_notify` callback in conjunction with the `Notice#fingerprint` method allows you to change the fingerprint of a notice to properly group the same notices. ```ruby Honeybadger.configure do |config| config.before_notify do |notice| notice.fingerprint = [notice.error_class, notice.component, notice.backtrace.join(',')].join(':') end end ``` The `notice` parameter gives you access to useful details about the exception, such as the `url` where it occurred and the `parsed_backtrace`, an array of hashes representing each line in its backtrace. For a full list of available properties, see the [API reference](https://www.rubydoc.info/gems/honeybadger/Honeybadger/Notice). ## Customizing the grouping for `Honeybadger.notify` [Section titled “Customizing the grouping for Honeybadger.notify”](#customizing-the-grouping-for-honeybadgernotify) The `:fingerprint` option can be used to override the fingerprint for an exception reported with `Honeybadger.notify`: ```ruby Honeybadger.notify(exception, fingerprint: 'a unique string') ``` # Customizing object display > Customize how objects are displayed in Ruby error reports to improve readability and protect sensitive data. By default, Honeybadger supports displaying the following core Ruby objects (uncoincidentally, these objects are also supported by JSON): ```plaintext Hash Array Set Numeric TrueClass FalseClas NilClass String ``` When an object of a different class is sent as data to Honeybadger (via context, request data, local variables, etc.), it’s first converted to a string using the `String()` function. For instance, given a `User` object which defines the `#to_s` method to return the user’s email address: ```ruby class User < ApplicationRecord def to_s email end end user = User.create(email: "user@example.com") Honeybadger.context({ user: user }) ``` …Honeybadger will display the context as: ```json { "user": "user@example.com" } ``` If this value is undesirable (since there’s no way to know the class of the object), the `#to_honeybadger` method can be defined to customize the value that is reported to Honeybadger: ```ruby class User < ApplicationRecord def to_s email end def to_honeybadger "#" end end ``` …now the context will display as: ```json { "user": "#" } ``` Note that while by default the contents of `#inspect` are filtered to prevent leaking sensitive attributes, attributes are **not** filtered when returning `#inspect` from `#to_honeybadger`, so it’s always best to explicitly interpolate the attributes that you want to display unless you know that the inspected output will never contain sensitive information. # Environments > Configure environment-specific error tracking settings for Ruby applications across development, staging, and production. In Honeybadger, errors are grouped by the environment they belong to. You don’t have to set an environment, but it can be useful if you’re running different versions of your app: for instance, you may have a “production” and a “staging” environment. Our integrations typically set the environment automatically if your framework has an environment (such as `Rails.env`). To set the environment manually, set the `env` configuration option: ```yaml --- api_key: "your-api-key" env: "production" ``` Another option for configuring the environment that gets reported to Honyebadger is to set the `HONEYBADGER_ENV` environment variable. If this variable is set, its value will override the `RAILS_ENV` variable. ## Development environments [Section titled “Development environments”](#development-environments) Some environments should usually not report errors at all, such as when you are developing on your local machine or running your test suite (locally or in CI). The *honeybadger* gem has an internal list of environment names which it considers development environments: ```plaintext development test cucumber ``` Honeybadger **does not** report errors in these environments unless you explicitly enable data reporting: ```yaml --- api_key: "your-api-key" report_data: true ``` # Filtering sensitive data > Filter sensitive data from Ruby error reports to protect user privacy and comply with security requirements. You have complete control over the data that Honeybadger reports when an error occurs. You can [filter specific attributes](#filtering-specific-attributes) or [disable the reporting](#disable-data-completely) of entire sections of data. ## Filtering specific attributes [Section titled “Filtering specific attributes”](#filtering-specific-attributes) By default, we filter the `password` and `password_confirmation`, as well as any params specified in Rails’ [`filter_parameters`](https://guides.rubyonrails.org/action_controller_overview.html#parameters-filtering). You can configure the gem to filter additional data from the params, session, environment and cookies hashes. To do so, use the `request.filter_keys` setting. When you add an attribute name to `request.filter_keys`, that attribute will be removed from any exceptions before they are reported to us. Here’s an example honeybadger.yml: ```yaml request: filter_keys: - password - password_confirmation - credit_card_number ``` The configuration above will filter out `params[:credit_card_number]`, `session[:credit_card_number]`, `cookies[:credit_card_number]`, and `Rails.env["credit_card_number"]`, as well as the password and password\_confirmation attributes. Regular expressions (regex) are also allowed. The configuration below will filter out any keys that are named anything matching `/credit_card/i`. ```yaml request: filter_keys: - !ruby/regexp "/credit_card/i" ``` ## Disable data completely [Section titled “Disable data completely”](#disable-data-completely) You can turn off reporting of params, session and environment data entirely. Here are the configuration options to do it: ```yaml request: disable_session: true # Don't report session data disable_params: true # Don't report request params disable_environment: true # Don't report anything from Rack ENV disable_url: true # Don't report the request URL ``` # Ignoring errors > Ignore specific errors in Ruby applications to reduce noise and focus on actionable error reports. Sometimes there are errors that you would rather not send to Honeybadger because they are not actionable or are handled internally. The *honeybadger* gem has multiple ways to ignore errors, depending on the situation: * [Ignore by class](#ignore-by-class) * [Ignore by browser](#ignore-by-browser) * [Ignore by environment](#ignore-by-environment) * [Ignore programmatically](#ignore-programmatically) ## Ignore by class [Section titled “Ignore by class”](#ignore-by-class) Some exceptions aren’t very useful and are best ignored. By default, we ignore the following: ```ruby 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 Rack::QueryParser::ParameterTypeError Rack::QueryParser::InvalidParameterError CGI::Session::CookieStore::TamperedWithCookie Mongoid::Errors::DocumentNotFound Sinatra::NotFound ``` To ignore additional errors, use the `exceptions.ignore` configuration option. The gem will ignore any exceptions matching the string, regex or class that you add to `exceptions.ignore`. ```yaml exceptions: ignore: - "MyError" - !ruby/regexp "/Ignored$/" - !ruby/class "IgnoredError" ``` Subclasses of ignored classes will also be ignored, while strings and regexps are compared with the error class name only. To override the default ignored exceptions, use the `exceptions.ignore_only` option instead: ```yaml exceptions: ignore_only: - "MyError" ``` In this case *only* the MyError class will be ignored, and all the classes that were ignored by default will no longer be ignored. ## Ignore by browser [Section titled “Ignore by browser”](#ignore-by-browser) To ignore certain user agents, use the `exceptions.ignored_user_agents` config option. You can specify strings or regular expressions: ```yaml exceptions: ignored_user_agents: - "Exact User Agent" - !ruby/regexp "/Bing/i" ``` ## Ignore by environment [Section titled “Ignore by environment”](#ignore-by-environment) Honeybadger ignores errors in development and test environments by default. You can enable or disable error reporting for a specific environment by using the `[environment name].report_data` configuration option: ```yaml staging: report_data: false ``` You may alternatively set `HONEYBADGER_REPORT_DATA=false` in your app’s ENV. We ask that you not enable error reporting for your test environment. It doesn’t do anyone any good. :) ## Ignore programmatically [Section titled “Ignore programmatically”](#ignore-programmatically) To ignore errors with some custom logic, you can use the `before_notify` callback. 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 calls the `notice.halt!` method, the exception won’t be reported: ```ruby # Here's how you might ignore exceptions based on their error message: Honeybadger.configure do |config| config.before_notify do |notice| notice.halt! if notice.error_message =~ /sensitive data/ end end ``` You can access any attribute on the `notice` argument by using the `[]` syntax. ```ruby Honeybadger.configure do |config| config.before_notify do |notice| notice.halt! if notice.exception.class < MyError && notice.params[:name] =~ "bob" && notice.context[:current_user_id] != 1 end end ``` # Reporting errors > Report errors from Ruby applications to Honeybadger with automatic notifications and custom error handling. Use `Honeybadger.notify(exception)` to send any exception to Honeybadger. For example, to notify Honeybadger of a rescued exception without re-raising: controller.rb ```ruby begin fail 'oops' rescue => exception Honeybadger.notify(exception) end ``` ## Reporting errors without an exception [Section titled “Reporting errors without an exception”](#reporting-errors-without-an-exception) You can report any type of error to Honeybadger, not just exceptions. The simplest form is calling `Honeybadger.notify` with an error message: ```ruby Honeybadger.notify("Something is wrong here") ``` The error’s class name will default to “Notice”, and a backtrace will be generated for you from the location in your code where `Honeybadger.notify` was called. ## Passing additional options to `Honeybadger.notify` [Section titled “Passing additional options to Honeybadger.notify”](#passing-additional-options-to-honeybadgernotify) In some cases you will want to override the defaults or add additional information to your error reports. To do so, you can pass a second options `Hash` to `Honeybadger.notify`. For example, building on the example in [Reporting errors without an exception](#reporting-errors-without-an-exception), you could override the default class name: ```ruby Honeybadger.notify("Something is wrong here", error_class: "MyError") ``` These are all the available options you can pass to `Honeybadger.notify`: | Option name | Description | Default value | | ---------------- | -------------------------------------------------------------- | ------------- | | `:error_message` | The `String` error message. | `nil` | | `:error_class` | The `String` class name of the error. | `"Notice"` | | `:backtrace` | The `Array` backtrace of the error. | `caller` | | `:fingerprint` | The `String` grouping fingerprint of the exception. | `nil` | | `:force` | Always report the exception when `true`, even when ignored. | `false` | | `:sync` | Send data synchronously (skips the worker) when `true`. | `false` | | `:tags` | The `String` comma-separated list of tags. | `nil` | | `:context` | The `Hash` context to associate with the exception. | `nil` | | `:controller` | The `String` controller name (such as a Rails controller). | `nil` | | `:component` | The `String` component name (such as a Rails controller name). | `nil` | | `:action` | The `String` action name (such as a Rails controller action). | `nil` | | `:parameters` | The `Hash` HTTP request paramaters. | `nil` | | `:session` | The `Hash` HTTP request session. | `nil` | | `:url` | The `String` HTTP request URL. | `nil` | ## Getting the current backtrace [Section titled “Getting the current backtrace”](#getting-the-current-backtrace) There are two ways to get the current backtrace in Ruby: 1. `Thread.current.backtrace` returns the entire backtrace up to and including the current method. 2. `caller` returns the backtrace up to but NOT including the current method. Either method can be passed to `Honeybadger.notify` using the `backtrace` option. Honeybadger sends the exception backtrace by default, or `caller` if there is no exception object available. # Tagging errors > Add tags to Ruby error reports to categorize and filter errors for better organization and analysis. Each error in Honeybadger has tags. Tags can be used to filter results when searching and can even apply to integrations so that only errors with a combination of certain tags trigger an email or a Slack message, for example. Tags can be used to create custom workflows, such as: * Find all errors tagged “badgers” and resolve them. * Tag critical errors as “critical” and configure PagerDuty to alert you only when a critical error happens. * If you have errors which aren’t actionable (but you still want to know about them), you could tag them with “low\_priority” and exclude those errors when automatically creating issues via the GitHub integration. * Tag all errors that happen in an area of your app with the name of the team that is responsible for them, then notify their Slack channel for only those errors. These are just examples: you can use tags however you want! While you can always add tags to existing errors through the Honeybadger UI, they are most useful when you add them programmatically as the exceptions happen. There are two ways to add tags to errors from your Ruby app: ## Tagging errors in global context [Section titled “Tagging errors in global context”](#tagging-errors-in-global-context) Every exception which is reported within the current context will have the specified tags added. Use the `tags` key to set the tags: ```ruby # Using a comma-separated string Honeybadger.context({ tags: 'critical, badgers' }) # Or using an array of strings Honeybadger.context({ tags: ['critical', 'badgers'] }) ``` ## Tagging errors in `Honeybadger.notify` [Section titled “Tagging errors in Honeybadger.notify”](#tagging-errors-in-honeybadgernotify) The tags will be added for just the current error being reported: ```ruby # Using a comma-separated string Honeybadger.notify(exception, tags: 'critical, badgers' ) # Or using an array of strings Honeybadger.notify(exception, tags: ['critical', 'badgers'] ) ``` ## Tag processing [Section titled “Tag processing”](#tag-processing) Tags are processed as follows: * Comma-separated strings are split into individual tags * Whitespace is automatically trimmed from each tag * Tags from context and explicit tags are merged and deduplicated * Empty tags are ignored # Tracking deployments > Track deployments from Ruby applications to correlate errors with releases and identify problematic code changes. 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. ## Deploying with GitHub Actions [Section titled “Deploying with GitHub Actions”](#deploying-with-github-actions) If your CI/CD pipeline is hosted with GitHub Actions, you can use the [Honeybadger Deploy Action](https://github.com/marketplace/actions/honeybadger-deploy-action) to notify our API about deployments. ## Deployment tracking via command line [Section titled “Deployment tracking via command line”](#deployment-tracking-via-command-line) We provide a CLI command to send deployment notifications manually. Try the following command for the available options: ```sh bundle exec honeybadger help deploy ``` Here’s an example of using the CLI to send a deployment notification: ```sh bundle exec honeybadger deploy \ --repository https://github.com/myorganization/myrepo \ --revision $(cat REVISION) \ --environment production \ --user $(whoami) ``` ## Heroku deployment tracking [Section titled “Heroku deployment tracking”](#heroku-deployment-tracking) Deploy tracking via Heroku is implemented using Heroku’s [app webhooks](https://devcenter.heroku.com/articles/app-webhooks). To set up the webhook, run the following CLI command from your project root: ```sh 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: ```sh heroku webhooks:add -i api:release -l notify -u "https://api.honeybadger.io/v1/deploys/heroku?repository=git@github.com/username/projectname&environment=production&api_key=asdf" --app app-name ``` If you are using our EU stack, you should use `eu-api.honeybadger.io` instead of `api.honeybadger.io` in the webhook URL. For more about manual use of Heroku deploy tracking, see the [Heroku Deployments](/guides/heroku/#heroku-deployment-tracking) guide. You should replace the `repository`, `api_key`, and `app` options with your own values. You may also want to change the environment (set to production by default). ## Kamal deployment tracking [Section titled “Kamal deployment tracking”](#kamal-deployment-tracking) You can use Kamal’s post-deploy hook to send a deployment notification to Honeybadger. Add the following snippet to `.kamal/hooks/post-deploy`: ```bash bundle exec honeybadger deploy \ --repository https://github.com/your_org/your_repo \ --revision $KAMAL_VERSION \ --environment production \ --user $KAMAL_PERFORMER ``` ## Capistrano deployment tracking [Section titled “Capistrano deployment tracking”](#capistrano-deployment-tracking) In order to track deployments using Capistrano, simply require Honeybadger’s Capistrano task in your `Capfile` file: ```ruby 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: ```ruby 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” | | `honeybadger_skip_rails_load` | Skip loading the Rails environment during deploy notification. | ## Ruby deployment tracking [Section titled “Ruby deployment tracking”](#ruby-deployment-tracking) You can also track a deployment from the *honeybadger* Ruby gem with `Honeybadger.track_deployment`: ```ruby Honeybadger.track_deployment( environment: Rails.env, revision: `git rev-parse HEAD`.strip, local_username: `whoami`.strip, repository: "git@github.com:user/example.git" ) ``` # Honeybadger CLI reference > Command-line interface reference for Honeybadger's Ruby gem with deployment tracking and testing commands. 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`. ## Commands [Section titled “Commands”](#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`. ## Configuration [Section titled “Configuration”](#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](/lib/ruby/gem-reference/configuration/#configuration-options) All other options must be passed as command-line flags. ### Rails initialization [Section titled “Rails initialization”](#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. # Configuration > Complete configuration reference for Honeybadger's Ruby gem with all available options and settings. 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](https://embed-ssl.wistia.com/deliveries/5fccf29d2b27d0f7ec62b5b39e2f5d9cd1f6f5b7.jpg?image_play_button=true\&image_play_button_color=7b796ae0\&image_crop_resized=150x84)](https://honeybadger.wistia.com/medias/vv9qq9x39d) ## YAML configuration file [Section titled “YAML configuration file”](#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: ```yaml --- api_key: "PROJECT_API_KEY" ``` ### Nested options [Section titled “Nested options”](#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: ```yaml --- logging: path: "/path/to/honeybadger.log" request: filter_keys: - "credit_card" ``` ### Environments [Section titled “Environments”](#environments) Environment-specific options can be set by name-spacing the options beneath the environment name. For example: ```yaml --- api_key: "PROJECT_API_KEY" production: logging: path: "/path/to/honeybadger.log" level: "WARN" ``` ### ERB and Regex [Section titled “ERB and Regex”](#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: ```yaml --- api_key: "PROJECT_API_KEY" request: filter_keys: - !ruby/regexp "/credit_card/i" ``` ## Configuring with environment variables (12-factor style) [Section titled “Configuring with environment variables (12-factor style)”](#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`: ```plaintext 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. For example, if the `HONEYBADGER_ENV` environment variable is present, it will override the `env` configuration option and `RAILS_ENV` environment variable. ## Configuration via Ruby (programmatic) [Section titled “Configuration via Ruby (programmatic)”](#configuration-via-ruby-programmatic) To configure Honeybadger from Ruby, use `Honeybadger.configure`: ```ruby # i.e. config/initializers/honeybadger.rb Honeybadger.configure do |config| config.api_key = "PROJECT_API_KEY" config.exceptions.ignore += [CustomError] end ``` Note that configuration via Ruby means that until your configuration code is run, Honeybadger will use its default configuration (or the YAML file or environment variables), so for the best experience, this should be as early as possible after startup. There are also a few special features which can only be configured via Ruby: ### Changing notice data [Section titled “Changing notice data”](#changing-notice-data) Use `before_notify` callbacks to modify [notice data](https://www.rubydoc.info/gems/honeybadger/Honeybadger/Notice) before it’s sent to Honeybadger: ```ruby Honeybadger.configure do |config| config.before_notify do |notice| # Use your own error grouping notice.fingerprint = App.exception_fingerprint(notice) # Ignore notices with sensitive data notice.halt! if notice.error_message =~ /sensitive data/ # Avoid using all your quota for non-production errors by allowing # only 10 errors to be sent per minute notice.halt! if !Rails.env.production? && Redis.current.incr(key = "honeybadger_errors:#{(Time.now - Time.now.sec).to_i}") > 10 Redis.current.expire(key, 120) end end ``` `before_notify` can be called multiple times to add multiple callbacks. ### Changing event data [Section titled “Changing event data”](#changing-event-data) Use `before_event` callbacks to modify [event data](https://www.rubydoc.info/gems/honeybadger/Honeybadger/Event) before it’s sent to Honeybadger: ```ruby Honeybadger.configure do |config| config.before_event do |event| # DB-backed job backends can generate a lot of noisy queries if event.event_type == "sql.active_record" && event[:query]&.match?(/good_job|solid_queue/) event.halt! end # Truncate long queries if event.event_type == "sql.active_record" && event[:query].present? event[:query] = event[:query].first(256) end # Set some data for each event if environment = ENV["HONEYBADGER_ENV"] || Rails.env event[:environment] = environment end # See https://api.rubyonrails.org/classes/ActiveSupport/CurrentAttributes.html for more info about using Current event[:user] = { id: Current.user.id, email: Current.user.email } if Current.user # Avoid using all your quota for non-production events by allowing # only 10 events to be sent per minute event.halt! if !Rails.env.production? && Redis.current.incr(key = "honeybadger_event:#{(Time.now - Time.now.sec).to_i}") > 10 Redis.current.expire(key, 120) end end ``` `before_event` can be called multiple times to add multiple callbacks. ### Using a custom `logger` [Section titled “Using a custom logger”](#using-a-custom-logger) While you can configure the default logger using the provided options, it’s also possible to replace the logger entirely: ```ruby Honeybadger.configure do |config| config.logger = MyLogger.new('/path/to/honeybadger.log') end ``` ### Using a custom `backend` [Section titled “Using a custom backend”](#using-a-custom-backend) This option allows you to change the backend which handles all reported data. This is an advanced option—you’ll need to [read the code](https://github.com/honeybadger-io/honeybadger-ruby/tree/master/lib/honeybadger/backend) to use it: ```ruby Honeybadger.configure do |config| config.backend = CustomBackend.new end ``` ## Configuration options [Section titled “Configuration options”](#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 | Prevent the Ruby program from exiting until all queued notices have been delivered to Honeybadger. (This can take a while in some cases; see `max_queue_size`.) *Default: `true`* | | `max_queue_size` | Integer | Maximum number of notices to queue for delivery at one time; new notices will be dropped if this number is exceeded. *Default: `100`* | | `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: `[]`* | | | | | | **INSIGHTS AND EVENTS** | | | | `insights.enabled` | Boolean | Enable automatic Insights instrumentation. *Default: `true` (version >= 6)* | | `insights.registry_flush_interval` | Integer | Number of seconds to flush the aggregated metrics registry. Set a higher number for greater resolution but use more data. *Default: `60`* | | `insights.console.enabled` | Boolean | Enable Insights instrumentation in a Rails console. *Default: `false`* | | `events.max_queue_size` | Integer | Number of events before the event queue will start dropping events. *Default: `100000`* | | `events.batch_size` | Integer | Number of events to batch that will trigger the gem to send. *Default: `1000`* | | `events.timeout` | Integer | Number of milliseconds before the event queue will send events regardless of size. *Default: `30000`* | | `events.attach_hostname` | Boolean | Attach server hostname to every event sent by the gem. *Default: `true`* | | `events.attach_environment` | Boolean | Attach the configured environment name to every event sent by the gem (including metrics). *Default: `true`* | | `events.ignore` | Array | An list of rules to match against events to be ignored. See [Ignoring Events](/lib/ruby/insights/filtering-events/) for more information. | | `events.ignore_only` | Array | A list of events to ignore (overrides the default ignored events). *Default: `nil`* | | `events.sample_rate` | Integer | Percentage of events to send. See [Sampling Events](/lib/ruby/insights/sampling-events/) for more information. | | | | | | **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`* | | `logging.tty_level` | String | Level to log when attached to a terminal (anything < `logging.level` will always be ignored). *Default: `DEBUG`* | | `logging.debug` | Boolean | Override debug logging for the logging subsystem. *Default: `nil`* | | | | | | **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`* | | `connection.ui_host` | String | The host to use when viewing data. *Default: `app.honeybadger.io`* | | `connection.ssl_ca_bundle_path` | String | Use this CA bundle when establishing secure connections. *Default: `nil`* | | `connection.system_ssl_cert_chain` | Boolean | Use the system’s SSL certificate chain (if available). *Default: `false`* | | | | | | **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](/lib/ruby/errors/collecting-user-feedback/) *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](/lib/ruby/errors/collecting-user-feedback/) *Default: `true`* | | | | | | **EXCEPTION REPORTING** | | | | `exceptions.enabled` | Boolean | Enable error reporting functionality. *Default: `true`* | | `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](https://rubygems.org/gems/binding_of_caller). *Default: `false`* | | `exceptions.unwrap` | Boolean | Reports #original*exception or #cause one level up from rescued exception when available. \_Default: `false`* | | | | | | **BREADCRUMBS** | | | | `breadcrumbs.enabled` | Boolean | Enable breadcrumb functionality. *Default: `true`* | | `breadcrumbs.active_support_notifications` | Hash | Configuration for automatic Active Support Instrumentation events. *Default: `Breadcrumbs::ActiveSupport.default_notifications`* | | `breadcrumbs.logging.enabled` | Boolean | Enable/Disable automatic breadcrumbs from log messages. *Default: `true`* | | **ACTIVE JOB** | | | | `active_job.attempt_threshold` | Integer | The number of attempts before notifications will be sent. *Default: `0`* | | `active_job.insights.enabled` | Boolean | Enable automatic Insights instrumentation for this plugin. *Default: `true`* | | `active_job.insights.events` | Boolean | Enable sending Active Job events to Insights. *Default: `true`* | | `active_job.insights.metrics` | Boolean | Enable sending Active Job metrics to Insights. *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`* | | `sidekiq.insights.enabled` | Boolean | Enable automatic Insights instrumentation for Sidekiq. *Default: `true`* | | `sidekiq.insights.collection_interval` | Integer | The frequency, in seconds, in which Sidekiq metrics are sampled. *Default: `60`* | | `sidekiq.insights.cluster_collection` | Boolean | Enable cluster wide metric collection. If you are using Sidekiq Enterprise, this is configured automatically. *Default: `true`* | | `sidekiq.insights.events` | Boolean | Enable sending Sidekiq events to Insights. *Default: `true`* | | `sidekiq.insights.metrics` | Boolean | Enable sending Sidekiq metrics to Insights. *Default: `false`* | | **SOLID\_QUEUE** | | | | `solid_queue.insights.enabled` | Boolean | Enable automatic Insights instrumentation for SolidQueue. *Default: `true`* | | `solid_queue.insights.collection_interval` | Integer | The frequency, in seconds, in which SolidQueue metrics are sampled. *Default: `60`* | | `solid_queue.insights.cluster_collection` | Boolean | Enable cluster wide metric collection. *Default: `true`* | | `solid_queue.insights.events` | Boolean | Enable sending SolidQueue events to Insights. *Default: `true`* | | `solid_queue.insights.metrics` | Boolean | Enable sending SolidQueue metrics to Insights. *Default: `false`* | | **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`* | | **FAKTORY** | | | | `faktory.attempt_threshold` | Integer | The number of attempts before notifications will be sent. *Default: `0`* | | **RESQUE** | | | | `resque.resque_retry.send_exceptions_when_retrying` | Boolean | Send exceptions when retrying a job. *Default: `true`* | | **SINATRA** | | | | `sinatra.enabled` | Boolean | Enable Sinatra auto-initialization. *Default: `true`* | | **RAILS** | | | | `rails.subscriber_ignore_sources` | Array | `source`s (strings or regexes) that should be ignored when using the Rails error reporter. *Default: `[]`* | | `rails.insights.enabled` | Boolean | Enable automatic Insights instrumentation for Rails. *Default: `true`* | | `rails.insights.events` | Boolean | Enable sending Rails events to Insights. *Default: `true`* | | `rails.insights.metrics` | Boolean | Enable sending Rails metrics to Insights. *Default: `false`* | | **Autotuner** | | | | `autotuner.insights.enabled` | Boolean | Enable automatic Insights data collection for Autotuner. *Default: `true`* | | `autotuner.insights.events` | Boolean | Enable sending Autotuner events to Insights. *Default: `true`* | | `autotuner.insights.metrics` | Boolean | Enable sending Autotuner metrics to Insights. *Default: `false`* | | **Karafka** | | | | `karafka.insights.enabled` | Boolean | Enable automatic Insights instrumentation for Karafka. *Default: `true`* | | `karafka.insights.events` | Boolean | Enable sending Karafka events to Insights. *Default: `true`* | | `karafka.insights.metrics` | Boolean | Enable sending Karafka metrics to Insights. *Default: `false`* | | **Net::HTTP** | | | | `net_http.insights.enabled` | Boolean | Enable automatic Insights instrumentation for `Net::HTTP`. *Default: `true`* | | `net_http.insights.full_url` | Boolean | Log the request URL instead of just the domain. *Default: `false`* | | `net_http.insights.events` | Boolean | Enable sending Net::HTTP events to Insights. *Default: `true`* | | `net_http.insights.metrics` | Boolean | Enable sending Net::HTTP metrics to Insights. *Default: `false`* | | **PUMA** | | | | `puma.insights.enabled` | Boolean | Enable automatic Insights instrumentation for Puma. *Default: `true`* | | `puma.insights.events` | Boolean | Enable sending Puma events to Insights. *Default: `true`* | | `puma.insights.metrics` | Boolean | Enable sending Puma metrics to Insights. *Default: `false`* | | `puma.insights.collection_interval` | Integer | The frequency, in seconds, in which Puma stats are sampled. *Default: `1`* | | **ACTIVE AGENT** | | | | `active_agent.insights.enabled` | Boolean | Enable automatic Insights instrumentation for Active Agent. *Default: `true`* | | **FLIPPER** | | | | `flipper.insights.enabled` | Boolean | Enable automatic Insights instrumentation for Flipper. *Default: `true`* | # Integration guide > Learn how to integrate Honeybadger's Ruby gem with custom frameworks and applications. This guide will teach you how to integrate your gem, framework, or other Ruby project with the [*honeybadger* Ruby gem](https://github.com/honeybadger-io/honeybadger-ruby). ## Who is this guide for? [Section titled “Who is this guide for?”](#who-is-this-guide-for) This guide is for anyone who is interested in extending the capability of the Honeybadger gem in order to share their integration with the Honeybadger community. In addition to covering *how* to create your integration, you’ll learn two ways to package and distribute it: 1. Submit a pull-request (PR) to the official Honeybadger gem 2. Publish your integration as a new gem that you maintain ## What can I build? [Section titled “What can I build?”](#what-can-i-build) Honeybadger’s plugin system integrates with popular gems (and even Ruby itself) in order to report exceptions with rich contextual information. Here are some examples of plugins which have been created so far: * [Report exceptions in Sidekiq jobs](https://github.com/honeybadger-io/honeybadger-ruby/blob/master/lib/honeybadger/plugins/sidekiq.rb), including the job parameters and configuration data * [Automatically associate errors with users](https://github.com/honeybadger-io/honeybadger-ruby/blob/master/lib/honeybadger/plugins/warden.rb) for any application which uses a Warden-based authentication system (such as Devise) * Hook into Ruby’s exception system in order to [report Local Variables for all Ruby exceptions](https://github.com/honeybadger-io/honeybadger-ruby/blob/master/lib/honeybadger/plugins/local_variables.rb) ## Getting started [Section titled “Getting started”](#getting-started) The Honeybadger gem has a [plugin system](https://github.com/honeybadger-io/honeybadger-ruby/blob/master/lib/honeybadger/plugin.rb) which allows you to step into our initialization process. From there, you can use the full power of Ruby to integrate with Honeybadger in interesting ways. Honeybadger’s plugin API is simple—there are only a few methods you need to learn. To give you an idea of what this looks like, let’s build a simple plugin. ## Building your plugin [Section titled “Building your plugin”](#building-your-plugin) Imagine you’re using a framework which provides the following API for handling exceptions: ```ruby MyFramework.on_exception do |exception| # Exception handling code (report the exception, log it, etc.) end ``` This is a fairly common pattern; for instance, [SuckerPunch has a similar API](https://github.com/honeybadger-io/honeybadger-ruby/blob/master/lib/honeybadger/plugins/sucker_punch.rb#L10). Here’s a Honeybadger plugin which checks to see if `MyFramework` is available. If it is, it installs an exception handler which reports all exceptions to Honeybadger: ```ruby require 'honeybadger/plugin' require 'honeybadger/ruby' module Honeybadger module Plugins # Register your plugin with an optional name. If the name (such as # "my_framework") is not provided, Honeybadger will try to infer the name # from the current file. Plugin.register 'my_framework' do requirement do # Check to see if the thing you're integrating with is loaded. Return true # if it is, or false if it isn't. An exception in this block is equivalent # to returning false. Multiple requirement blocks are supported. defined?(MyFramework) end execution do # Write your integration. This code will be executed only if all requirement # blocks return true. An exception in this block will disable the plugin. # Multiple execution blocks are supported. MyFramework.on_exception do |exception| Honeybadger.notify(exception) end end end end end ``` There are three steps which Honeybadger performs when loading your plugin: 1. `Honeybadger::Plugin.register` registers the plugin with Honeybadger. 2. When initializing an application, Honeybadger will attempt to load your plugin, executing every `requirement` block you gave it. 3. If all `requirement` blocks returned `true`, then Honeybadger executes each `execution` block in turn. ### A simple Sidekiq plugin [Section titled “A simple Sidekiq plugin”](#a-simple-sidekiq-plugin) [Sidekiq](https://sidekiq.org/) is a good example of a framework which integrates nicely with Honeybadger, providing a lot of rich contextual data with each exception. *Note: Keep in mind that [we already support Sidekiq natively](https://github.com/honeybadger-io/honeybadger-ruby/blob/master/lib/honeybadger/plugins/sidekiq.rb), so don’t try to actually run this example in a Honeybadger project, or you may get multiple exception reports. :)* lib/honeybadger/plugins/sidekiq.rb ```ruby require 'honeybadger/plugin' require 'honeybadger/ruby' module Honeybadger module Plugins # It's best practice to create your own Honeybadger::Plugins::YourFramework # namespace, if you need to create additional classes to use when executing # your plugin. module Sidekiq class Middleware def call(worker, msg, queue) Honeybadger.context.clear! yield end end Plugin.register do requirement { defined?(::Sidekiq) } execution do ::Sidekiq.configure_server do |sidekiq| sidekiq.server_middleware do |chain| chain.prepend Middleware end sidekiq.error_handlers << lambda {|ex, params| job = params[:job] Honeybadger.notify(ex, parameters: params, component: job['wrapped'] || job['class'] ) } end end end end end end ``` ## Sharing your plugin [Section titled “Sharing your plugin”](#sharing-your-plugin) Once you’ve built your plugin, it’s time to share it with other ‘badgers like you, for fame and glory (or at least a high-five). There are two good ways to share a plugin: 1. Submit a PR to the Honeybadger gem 2. Publish your own Ruby gem, such as “honeybadger-plugins-sidekiq” We’d love to help you decide which of these is the best way to go. We’re very open to including a wide variety of plugins in the official Honeybadger gem, so that everyone can enjoy them by default. Head over to GitHub and [tell us about your plugin by creating a new issue](https://github.com/honeybadger-io/honeybadger-ruby/issues/new). Here’s an example issue (this is just how I’d write it—you don’t need to include a link to your plugin if you haven’t finished it yet, or it isn’t on GitHub). > Hey ‘badgers! > > I use Sidekiq a lot in my daily work, and since there is no existing Honeybadger integration, I decided to make one. Would you be interested in including Sidekiq as a default plugin? > > Here’s a link to Sidekiq: > > > > Here’s a link to my plugin: > > > > Thanks! We’ll get back to you as soon as possible. If we decide that your plugin is something that would benefit everyone, we’ll ask you to submit a PR (if you aren’t sure how to do this, don’t worry—read on for instructions, and feel free to ask us for help! If we decided against a PR for some reason, you can publish your plugin as a gem, which is another great way to share it with the community. ### Submitting a PR [Section titled “Submitting a PR”](#submitting-a-pr) To submit a PR, you’ll need a few things: 1. A [GitHub account](https://github.com/) 2. [Git](https://help.github.com/articles/set-up-git/) and a [supported Ruby version](../supported-versions/) installed on your computer 3. A fork of the [honeybadger gem](https://github.com/honeybadger-io/honeybadger-ruby) repository After creating a fork (go to the [honeybadger-ruby repository](https://github.com/honeybadger-io/honeybadger-ruby) and use the **Fork** button, top-right of the page), run the following commands to set up your local copy of the gem: ```sh git clone https://github.com/your-username/honeybadger-ruby.git cd honeybadger-ruby bundle install ``` To make sure everything is set up correctly, try running the unit tests: ```plaintext bundle exec rake spec:units ``` You should see something like this: ```plaintext All examples were filtered out; ignoring {:focus=>true} Randomized with seed 14664 ................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................ Finished in 0.97639 seconds (files took 0.57739 seconds to load) 512 examples, 0 failures ``` Assuming the tests ran, you should be ready to add your plugin code. 1. Create a file in [*lib/honeybadger/plugins/*](https://github.com/honeybadger-io/honeybadger-ruby/tree/master/lib/honeybadger/plugins). The file name should use [snake\_case](https://en.wikipedia.org/wiki/Snake_case), and have a Ruby (`.rb`) file extension. If your plugin integrates with “MyFramework”, then the file path should be *lib/honeybadger/plugins/my\_framework.rb*. 2. Add your plugin code to the file you created. 3. A good PR should include tests. We use [RSpec](http://rspec.info/) for our test suite. For an example of a simple RSpec plugin test, [check out the tests for the SuckerPunch plugin](https://github.com/honeybadger-io/honeybadger-ruby/blob/master/spec/unit/honeybadger/plugins/sucker_punch_spec.rb). Use `bundle exec rake spec:units` to run the tests while developing your plugin. After adding some tests and/or verifying that your plugin doesn’t cause issues with Honeybadger, you’re ready to submit your plugin: 1. Add an entry to [CHANGELOG.md](https://github.com/honeybadger-io/honeybadger-ruby/blob/master/CHANGELOG.md): ```plaintext ## [Unreleased] ### Added - Added a plugin for MyFramework ``` See [Keep a Changelog](http://keepachangelog.com/) for more info on the format of the changelog. 2. Commit your changes: ```sh git add . git commit --message "Add a MyFramework plugin." ``` 3. Push your changes: ```sh git push origin master ``` Now that your fork has the changes you want to add, create a pull request to the [honeybadger-io/honeybadger-ruby repository](https://github.com/honeybadger-io/honeybadger-ruby/pulls) on GitHub. If you’re not sure how to create a pull request, [check out GitHub’s guide](https://help.github.com/articles/creating-a-pull-request-from-a-fork/), and feel free to ask us for help! ### Publishing your own gem [Section titled “Publishing your own gem”](#publishing-your-own-gem) Before publishing your own gem, read through [the official RubyGems guide](https://guides.rubygems.org/publishing/). Here are some basic steps to create a gem and publish it to [RubyGems.org](https://rubygems.org/). If you get stuck, feel free to ask us for help! *Fun fact: did you know that Ruby Central uses Honeybadger to monitor RubyGems.org for exceptions?* #### Creating the gem [Section titled “Creating the gem”](#creating-the-gem) Bundler has a handy tool that will create a simple gem for you. 1. Make sure you have the `bundler` gem installed: ```sh gem install bundler ``` 2. Create a new gem using the `bundle gem` command. You should name your gem “honeybadger-plugins-\[name of your plugin]”. For example, if your plugin integrates with MyFramework, name your project: “honeybadger-my\_framework”: ```sh bundle gem honeybadger-plugins-my_framework ``` Follow the prompts to add tests (we use RSpec), create a license (we like MIT), and add a code of conduct for your gem. 3. Once your gem is created, check out the directory structure, and read the README: ```sh cd honeybadger-my_framework ls -l cat README.md ``` 4. Lastly, run the `bundle install` command: ```sh bundle install ``` It will fail the first time, asking you to edit the *honeybadger-plugins-my\_framework.gemspec* file. Make the requested edits and then re-run `bundle install` until it completes successfully. *Note: If you added a test framework, run the new test suite with `bundle exec rake`.* #### Adding your code [Section titled “Adding your code”](#adding-your-code) 1. Add your plugin code to *lib/honeybadger/plugins/my\_framework.rb*, which should have been created by the `bundle gem` command. 2. If you chose to add a test framework when creating your gem, add some tests. 3. After you verify that your plugin works, commit your changes: ```sh git add . git commit --message "Add a MyFramework plugin." ``` #### Pushing to RubyGems.org [Section titled “Pushing to RubyGems.org”](#pushing-to-rubygemsorg) To publish your first version (0.1.0) to [RubyGems.org](https://rubygems.org/): ```sh gem build honeybadger-plugins-my_framework.gemspec gem push honeybadger-plugins-my_framework-0.1.0.gem ``` You can view your new gem at the following URL: # Supported versions > View supported Ruby and Rails versions and compatibility requirements for Honeybadger's Ruby gem. The support tables below are for the latest version of the Honeybadger gem, which aims to support all maintained (non-EOL) versions of Ruby and supported frameworks. If you’re using an older version of Ruby or your framework, you may need to install an older version of the gem. ## Supported Ruby versions [Section titled “Supported Ruby versions”](#supported-ruby-versions) | Ruby Interpreter | Supported Version | | ---------------- | ----------------- | | MRI | >= 2.7.0 | | JRuby | >= 9.2 | ## Supported web frameworks [Section titled “Supported web frameworks”](#supported-web-frameworks) | Framework | Version | Native? | | ------------------------------------------------------------------- | -------- | ---------- | | [Rails](/lib/ruby/integration-guides/rails-exception-tracking/) | >= 5.2 | yes | | [Sinatra](/lib/ruby/integration-guides/sinatra-exception-tracking/) | >= 1.2.1 | yes | | [Rack](/lib/ruby/integration-guides/rack-exception-tracking/) | >= 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](https://github.com/honeybadger-io/honeybadger-ruby/blob/1.16-stable/docs/index.md). ## Supported job queues [Section titled “Supported job queues”](#supported-job-queues) | Library | Version | Native? | | ------------ | ------- | ------- | | Active Job | any | yes | | Delayed Job | any | yes | | Resque | any | yes | | Sidekiq | any | yes | | Shoryuken | any | yes | | Sucker Punch | any | yes | For other job queues, you can manually call [`Honeybadger.notify`](https://docs.honeybadger.io/lib/ruby/errors/reporting-errors/) in your error handler. For instance, if you’re using GoodJob: ```ruby config.good_job.on_thread_error = do |ex| Honeybadger.notify(ex) end ``` ## Other integrations [Section titled “Other integrations”](#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 also [integrate Honeybadger into any Ruby script](/lib/ruby/integration-guides/ruby-exception-tracking/) using `Honeybadger.notify`. See the [API reference](https://www.rubydoc.info/gems/honeybadger/Honeybadger/Agent) for a full list of methods available. # Honeybadger on the command line > Use Honeybadger's command-line tools for Ruby applications to test your integration, track deployments, and more. The *honeybadger* gem includes a Command Line Interface (CLI) that can be used for a variety of activities from installing Honeybadger in a new project to reporting failed cron jobs. For a full overview of the CLI and the commands it provides, see the [CLI reference](/lib/ruby/gem-reference/cli/). In this chapter we’re going to discuss some of the interesting ways to use the CLI in your Ruby project. ## Cron/command line monitoring [Section titled “Cron/command line monitoring”](#croncommand-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`): ```sh 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. To learn more, run `honeybadger help exec`. ## Notify from the command line [Section titled “Notify from the command line”](#notify-from-the-command-line) To send a Honeybadger notification from the command line/terminal, use `honeybadger notify`: ```sh honeybadger notify --message "This is an error from the command line" ``` To learn more, run `honeybadger help notify`. # Introduction > Get started with Honeybadger's Ruby gem for error tracking and application monitoring in Ruby and Rails applications. In this chapter we’re going to cover [the basics of installing the *honeybadger* gem](#installing-the-gem) and [how configuration works](#how-configuration-works). For full instructions and best practices for your framework or platform, see the **Integration guides**. ## Installing the gem [Section titled “Installing the gem”](#installing-the-gem) The first step is to add the honeybadger gem to your Gemfile: ```ruby gem 'honeybadger' ``` Tell bundler to install: ```bash bundle install ``` Next, you'll set the API key for this project. ```bash bundle exec honeybadger install [Your project API key] ``` This will do three things: 1. Generate a `honeybadger.yml` file. If you don't like config files, you can place your API key in the `$HONEYBADGER_API_KEY` environment variable. 2. If Capistrano is installed, we'll add a require statement to *Capfile*. 3. Send a test exception to your Honeybadger project. ## How configuration works [Section titled “How configuration works”](#how-configuration-works) Honeybadger’s configuration consists of named options. Some are top level options such as `api_key`, while others have nested namespaces (separated with a dot) such as `exceptions.ignore`. The only *required* option is `api_key`. There are three ways to configure options for the Honeybadger gem: 1. *honeybadger.yml* configuration file 2. Environment variables 3. Programmatically using `Honeybadger.configure` By default we use the *honeybadger.yml* file, so that’s what most of the examples will use in this guide, but the method you use is a matter of preference. Here’s an example *honeybadger.yml* file: ```yaml --- api_key: "PROJECT_API_KEY" ``` See the [Configuration reference](/lib/ruby/gem-reference/configuration/) for additional info. # Multiple projects > Configure multiple Honeybadger projects in Ruby applications for multi-tenant or complex architectures. To send errors to another Honeybadger project, configure an additional agent: ```ruby 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. # Performing check-ins > Perform check-ins from Ruby applications to monitor rake tasks and cron jobs with Honeybadger. [Honeybadger supports check-ins](/guides/check-ins/), which allow you to monitor things like cron jobs and other services. To perform a check-in, call `Honeybadger.check_in` with the ID of the check-in in your Honeybadger project. For example: ```ruby Honeybadger.check_in('1MqIo1') ``` ## Checking in from a Rake task [Section titled “Checking in from a Rake task”](#checking-in-from-a-rake-task) Here’s an example of checking in from a rake task: ```ruby task :my_task do # your code Honeybadger.check_in('1MqIo1') end ``` Now your task will check in when it’s executed periodically by cron, Heroku Scheduler, etc. If it ever stops checking in, Honeybadger will notify you. # Plain ruby mode > Use Honeybadger's Ruby gem in plain Ruby applications without Rails or other frameworks. In the Rails world it’s pretty much expected that when you install a gem it’s going to automatically integrate with your application. For instance, many gems provide their own [Railtie](http://edgeapi.rubyonrails.org/classes/Rails/Railtie.html) to run their own code when Rails initializes. The honeybadger gem fully embraces this approach by automatically detecting and integrating with as many 3rd-party gems as possible when it’s required: ```ruby require 'honeybadger' ``` Some Rubyists prefer to roll their own integrations, however. They may want to avoid 3rd-party [Monkey patching](https://en.wikipedia.org/wiki/Monkey_patch), while others aren’t using any of the libraries we integrate with and would rather report errors themselves using `Honeybadger.notify`, avoiding unnecessary initialization at runtime. To use Honeybadger without the integrations, simply `require 'honeybadger/ruby'` instead of the normal `require 'honeybadger'`. You will need to configure the gem from Ruby using `Honeybadger.configure` as *honeybadger.yml* and environment variable initialization are also skipped: ```ruby require 'honeybadger/ruby' Honeybadger.configure do |config| config.api_key = "PROJECT_API_KEY" end at_exit do # Wait for asynchronous error notifications before shutting down. Honeybadger.stop end begin # Failing code rescue => exception Honeybadger.notify(exception) end ``` See the [API Reference](https://www.rubydoc.info/gems/honeybadger) for additional methods you can use to integrate Honeybadger with your Ruby project manually. # Tests and Honeybadger > Test Honeybadger's Ruby gem integration with your application using the included test backend. 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](https://github.com/bblimke/webmock) to perform a similar test using the “server” backend. ## Configuring the test backend [Section titled “Configuring the test 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: ```yaml 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 [Section titled “Writing the integration test”](#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 ```ruby 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 ```ruby # ... get '/test/honeybadger' => 'honeybadger_test#index' if Rails.env.test? ``` Finally, create the integration test: spec/features/honeybadger\_spec.rb ```ruby 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 ``` # Insights overview > Query automatic Ruby instrumentation, framework events, and custom application events in Honeybadger Insights. [Insights](/guides/insights/) lets you observe what your Ruby application does in production. Honeybadger records common Ruby activity automatically, including requests, database queries, background jobs, cache calls, and runtime metrics. From there, you can add context and custom events from your own code, then use [BadgerQL](/guides/insights/badgerql/) to ask questions across the whole event stream. Any field you send is queryable as soon as it arrives, with no schema to define ahead of time. ## Start with automatic instrumentation [Section titled “Start with automatic instrumentation”](#start-with-automatic-instrumentation) Insights is on by default in v6.0+. The gem starts recording events as soon as your app boots. [Automatic instrumentation](/lib/ruby/insights/automatic-instrumentation/)Configure what the gem captures. We capture a wide range of events automatically. [Ruby event reference](/insights/event-types/ruby/)See every Ruby event type and field. ## Add a built-in dashboard [Section titled “Add a built-in dashboard”](#add-a-built-in-dashboard) Automatic events power built-in dashboards, no setup necessary. [Rails](/guides/dashboards/rails/)Slow requests, queries, and partials; cache hit rates by controller [Sidekiq](/guides/dashboards/sidekiq/)Job counts, durations, and failure rates by worker [Active Job](/guides/dashboards/active-job/)Job counts, durations, and failure rates by job class [Autotuner](/guides/dashboards/autotuner/)Heap growth, GC counts, and memory tuning suggestions [Puma](/guides/dashboards/puma/)Request backlog, running threads, and pool capacity over time Pre-aggregated alternatives for apps that have [metrics enabled](/lib/ruby/insights/collecting-and-reporting-metrics/): [Rails Metrics](/guides/dashboards/rails-metrics/)Pre-aggregated throughput, controller durations, and DB/view timings [Sidekiq Metrics](/guides/dashboards/sidekiq-metrics/)Pre-aggregated job durations, queue depth, latency, and capacity [Active Job Metrics](/guides/dashboards/active-job-metrics/)Pre-aggregated job throughput, durations, and stats by job class [Karafka](/guides/dashboards/karafka/)Consumer lag, processing durations, and broker errors by topic [Net::HTTP Metrics](/guides/dashboards/net-http-metrics/)Outbound HTTP throughput, durations, and status codes by host [Solid Queue Metrics](/guides/dashboards/solid-queue-metrics/)Job statuses, active workers and dispatchers, and queue depths ## Add application context [Section titled “Add application context”](#add-application-context) Adding event context attaches fields to the current thread. Once set, every event emitted from that thread includes them. Lets say our app is A/B testing a new checkout flow. We could record the A/B variant simply with event context: Set the variant on context ```ruby Honeybadger.event_context({ checkout_variant: }) ``` The `checkout_variant` field is now on every ActiveRecord event for that request. You can group by it like any other field. ActiveRecord work by checkout variant ```badgerql filter event_type::str == "sql.active_record" and isNotNull(checkout_variant::str) | stats count() as queries, avg(duration::float) as avg_ms by checkout_variant::str | sort queries desc ``` | queries | avg\_ms | checkout\_variant | | ------- | ------- | ----------------- | | 26815 | 1.93 | new | | 11873 | 1.71 | control | The new variant ran more than twice as many queries with similar per-query time. Keep in mind that adding another A/B variant will extend any of the examples here without the need to change anything on the Honeybadger side. [Event context](/lib/ruby/insights/event-context/)Block-scoped context, cross-thread propagation, and clearing. ## Record application events [Section titled “Record application events”](#record-application-events) Custom events record activity the framework cannot see at all. Rails knows a checkout request ran. Only your app knows whether the payment authorized: Send a custom payment event ```ruby Honeybadger.event("payment.authorized", { payment_provider: payment.provider, amount: checkout.total, currency: checkout.currency, authorization_id: payment.authorization_id }) ``` This query breaks down the amounts collected by variant and provider: Payments by variant and provider ```badgerql filter event_type::str == "payment.authorized" | stats count() as authorizations, sum(amount::float) as authorized_amount by checkout_variant::str, payment_provider::str | sort authorized_amount desc ``` | authorizations | authorized\_amount | checkout\_variant | payment\_provider | | -------------- | ------------------ | ----------------- | ----------------- | | 413 | 34108.00 | new | stripe | | 218 | 18722.00 | new | paypal | | 418 | 32167.00 | control | stripe | | 220 | 13639.00 | control | paypal | [Sending custom events](/lib/ruby/insights/sending-events-to-insights/)The full Honeybadger.event API, naming conventions, and delivery. # Automatic instrumentation > Events the Honeybadger Ruby gem captures automatically from Rails, background jobs, and more for Honeybadger Insights. [Honeybadger Insights](/guides/insights/) captures events from your Ruby application, including web requests, database queries, background jobs, and cache operations, and makes them available for querying, visualization, and [dashboards](/guides/dashboards/). In a Rails app, this gives you performance monitoring and observability out of the box without additional instrumentation libraries. In Honeybadger Ruby gem v6.0+, Insights is enabled by default. If you’re using an older gem version (v5.11+), you’ll need to enable it manually in your `honeybadger.yml` configuration file: ```yaml insights: enabled: true ``` ## Event captures [Section titled “Event captures”](#event-captures) Automatic instrumentation sends events from Rails, ActiveJob, Sidekiq, SolidQueue, Karafka, Net::HTTP, Puma, and more to Honeybadger, where they will be displayed in the [Insights](/guides/insights/) section of your project. See the [Ruby event reference](/insights/event-types/ruby/) for every event the gem emits, with field schemas and types. To find these events, filter by `event_type::str`. Here’s an example BadgerQL query that you can use: ```badgerql fields @ts, @preview | filter event_type::str == "perform.sidekiq" | sort @ts ``` ## Customizing Insights for a specific plugin [Section titled “Customizing Insights for a specific plugin”](#customizing-insights-for-a-specific-plugin) When Insights is active, all plugins are enabled if the required library is present. For example, if Sidekiq is present in your app, the Sidekiq plugin will be loaded. You can disable automatic Insights instrumentation for a specific plugin by adding a configuration like this: ```yaml sidekiq: insights: enabled: false ``` This will only affect Insights-related data capture and not the error notification portion of the plugin. Some plugins allow for an easy way to choose if you want to capture events, metrics, or both for a particular plugin. The following configuration options are available: ```yaml rails: insights: events: true metrics: false karafka: insights: events: true metrics: false sidekiq: insights: events: true metrics: false net_http: insights: events: true metrics: false solid_queue: insights: events: true metrics: false puma: insights: events: true metrics: false autotuner: insights: events: true metrics: false ``` Event options are all true by default. It is recommened to turn off events for plugins that may be producing more data than you actually need. Metric data collection is false by default since most metrics can be calculated from events. By default, the `net_http` plugin logs the domain name of any request as part of the event payload. You can enabling logging of the full URL by setting the following configuration: ```plaintext net_http: insights: full_url: true ``` ## Managing event volume [Section titled “Managing event volume”](#managing-event-volume) If some events are noisy or you’d like to reduce quota consumption: * [Filtering events](/lib/ruby/insights/filtering-events/) — ignore specific event types, or inspect and halt events with a callback. * [Sampling events](/lib/ruby/insights/sampling-events/) — send only a percentage of events. ## Sending your own events [Section titled “Sending your own events”](#sending-your-own-events) Automatic instrumentation covers the libraries the gem knows about. To send your own application events, see [Sending custom events](/lib/ruby/insights/sending-events-to-insights/). ## Metrics [Section titled “Metrics”](#metrics) The Honeybadger Ruby gem does more than just send events when they occur in your app. You can also enable metric collection. Check out [Collecting and Reporting Metrics](/lib/ruby/insights/collecting-and-reporting-metrics/) for more information. ## Sending Rails logs to Insights [Section titled “Sending Rails logs to Insights”](#sending-rails-logs-to-insights) If you are already using the Rails logger to track events in your application, you can send those events to Insights by [using a structured logging gem](/guides/insights/integrations/ruby-and-rails). # Collecting and reporting metrics > Collect and report custom metrics from Ruby applications to Honeybadger for performance monitoring. Honeybadger’s Ruby gem (v5.11+) can be used to collect metrics and send them to [Insights](https://docs.honeybadger.io/guides/insights/). ## Enabling Insights [Section titled “Enabling Insights”](#enabling-insights) To enable collecting of metrics, you’ll first need to enable Insights in your `honeybadger.yml` configuration file: ```yaml insights: enabled: true ``` ### Enable metrics collection [Section titled “Enable metrics collection”](#enable-metrics-collection) You can enable the metrics collection of each plugin by adding the relevant configuration to your `honeybadger.yml` file: ```yaml rails: insights: metrics: true karafka: insights: metrics: true sidekiq: insights: metrics: true net_http: insights: metrics: true solid_queue: insights: metrics: true puma: insights: metrics: true autotuner: insights: metrics: true ``` Enabling this will collect metric data for the libraries below and display it in the [Insights](/guides/insights/) section of your project. Each metric is emitted as a [`metric.hb`](/insights/event-types/ruby/metric.hb/) event with a `metric_source` identifying the plugin and a `metric_name` identifying the metric. These metrics may be found using the following BadgerQL query: ```badgerql fields @ts, @preview | filter event_type::str == "metric.hb" | filter metric_source::str == "sidekiq" | filter metric_name::str == "active_workers" | sort @ts ``` ### Customizing Insights for a specific plugin [Section titled “Customizing Insights for a specific plugin”](#customizing-insights-for-a-specific-plugin) When Insights is active, all plugins are enabled if the required library is present. For example, if Sidekiq is present in your app, the Sidekiq plugin will be loaded. You can disable automatic Insights instrumentation for a specific plugin by adding a configuration like this: ```yaml sidekiq: insights: enabled: false ``` This will only affect Insights-related data capture and not the error notification portion of the plugin. Some plugins allow for an easy way to choose if you want to capture events, metrics, or both for a particular plugin. The following configuration options are available: ```yaml rails: insights: events: true metrics: false karafka: insights: events: true metrics: false sidekiq: insights: events: true metrics: false net_http: insights: events: true metrics: false solid_queue: insights: events: true metrics: false puma: insights: events: true metrics: false autotuner: insights: events: true metrics: false ``` Event options are all true by default. It is recommened to turn off events for plugins that may be producing more data than you actually need. Metric data collection is false by default since most metrics can be calculated from events. ### Customizing cluster metrics collection [Section titled “Customizing cluster metrics collection”](#customizing-cluster-metrics-collection) For certain stats, collection is limited by a polling interval. Honeybadger will periodically collect stats. This can be tailored per plugin through a configuration parameter: ```yaml sidekiq: insights: collection_interval: 5 solid_queue: insights: collection_interval: 5 puma: insights: collection_interval: 1 ``` By reducing or increasing the frequency the gem collect stats will all you to fine tune the accuracy of your stats and the resources used to do so. Some metrics collection methods collect data based on the entire cluster of an application. In these cases, you would only need to collect data from a single instance of the Honeybadger gem. This helps save on unecessary load as well as data usage. Plugins collect data by default, but can be customized through configuration. ```yaml sidekiq: insights: cluster_collection: false solid_queue: insights: cluster_collection: false ``` You can use this configuration paramter to control which instances you want collecting cluster based data. If you are using Sidekiq Enterprise, we automatically detect the leader instance and will enable cluster collection on that instance and disable it on others without any additional configuration. ## Data aggregation [Section titled “Data aggregation”](#data-aggregation) When you collect metrics using the Honeybadger gem, the gem will aggregate the data and report the results to Insights every 60 seconds. This allows you to collect data as much and as quickly as you want, while making efficient use of your daily data quota. If you want to tweak the resolution of the timing, you can configure it in the `honeybadger.yml` config file. ```yaml insights: registry_flush_interval: 120 ``` The above configuration will adjust the metric registry so that it reports every 2 minutes and help save on data usage. ## Manually collecting your own metrics [Section titled “Manually collecting your own metrics”](#manually-collecting-your-own-metrics) The Honeybadger gem provides a API for defining and collecting your own metrics to feed into Insights. ### Types of metrics [Section titled “Types of metrics”](#types-of-metrics) #### Gauge [Section titled “Gauge”](#gauge) A gauge tracks a specific value at a point in time. During aggregation, the metric will record the values: `max`, `min`, `avg`, and `latest`. ```ruby Honeybadger.gauge('data_size', ->{ file.byte_size }) ``` #### Timer [Section titled “Timer”](#timer) Timers are similar to gauges in that they track a specific value in time. However, the `time` methods provides a convenient way to measure duration across your ruby operations. ```ruby Honeybadger.time('process_application', ->{ application.process }) ``` #### Counter [Section titled “Counter”](#counter) Counters are simple numbers that you can increment or decrement by any value you wish. ```ruby Honeybadger.increment_counter('add_to_basket', { item_id: item.id }) ``` #### Histogram [Section titled “Histogram”](#histogram) Histograms allows you to collate data values into predefined bins. The default bins are `[0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10]`. You can define your own set by passing a `bins` attribute to the metric. You may pass a callable lambda, which will be timed and the duration recorded. Or you may also pass a `duration` keyword argument if you have the value at hand. ```ruby Honeybadger.histogram('execute_request', ->{ request.execute }) # or Honeybadger.histogram('execute_request', duration: duration) ``` #### Helper module [Section titled “Helper module”](#helper-module) You can also include the helper module `Honeybadger::InstrumentationHelper` into any of your classes. The module provdes shortened forms to create the same metrics as metioned above, as well as other helper methods to customize your metrics. Here is an example of how we can rewrite the example metrics above, while adding more custom attributes: ```ruby class MyMetrics include Honeybadger::InstrumentationHelper attr_reader :region def initialize(region) @region = region end def example metric_source 'custom_metrics' metric_attributes { region: region } gauge 'data_size', ->{ file.byte_size } time 'process_application', ->{ application.process } increment_counter 'add_to_basket', { item_id: item.id } histogram 'execute_request', ->{ request.execute } end end ``` Aside from a less verbose API, there are two available helper methods that will aid in organizing your metrics. The `metric_source` method accepts the name of where your metrics are coming from. This can be the name of a library, or the class you are calling from. The `metric_attributes` method accepts a hash that will be passed to all metrics that follow. Then you can find these metrics by using the following BadgerQL query: ```badgerql fields @ts, @preview | filter event_type::str == "metric.hb" | filter metric_source::str == "custom_metrics" | filter region::str == "some-region" | sort @ts ``` ## Ignoring metrics [Section titled “Ignoring metrics”](#ignoring-metrics) You can use the `before_event` callback to inspect or modify metric data, as well as calling `halt!` to prevent the metric from being sent to Honeybadger: ```ruby Honeybadger.configure do |config| config.before_event do |event| if event.event_type == "metric.hb" && event[:metric_name] == "jobs_processed" event.halt! end end end ``` `before_event` can be called multiple times to add multiple callbacks. Similarly, you may also ignore metric events by configuring your `honeybadger.yml` config file by specifying a hash object: ```yaml events: ignore: - event_type: "metric.hb" metric_name: "jobs_processed" ``` ## Puma [Section titled “Puma”](#puma) Puma has it’s own plugin system and requires a small change to your `puma.rb`. The Honeybadger gem comes with Puma plugin and can be enabled by adding the following to your `puma.rb`: ```ruby plugin :honeybadger ``` ## Autotuner [Section titled “Autotuner”](#autotuner) To enable Autotuner, follow the directions in the [README.md](https://github.com/Shopify/autotuner) file. You can skip the parts about setting `Autotuner.reporter` and `Autotuner.metrics_reporter` as the Honeybadger gem will configure this for you. ## More automatic instrumentation [Section titled “More automatic instrumentation”](#more-automatic-instrumentation) The Honeybadger Ruby gem provides more instrumentation than just metrics. When you enable Insights, you also enable automatic event logging. Check out [Automatic instrumentation](/lib/ruby/insights/automatic-instrumentation/) for more information. # Event context > Add custom metadata to the events sent from your Ruby application to Honeybadger Insights. You can add custom metadata to the events sent to Honeybadger Insights by using the `Honeybadger.event_context` method. This metadata will be included in each event sent within the same thread. Caution This will add the metadata to all events sent, so be careful not to include too much data. Try to keep it to simple key/value pairs. For example, you can add user ID information to all events (via a Rails controller): ```ruby class ApplicationController < ActionController::Base before_action :set_honeybadger_context private def set_honeybadger_context if current_user Honeybadger.event_context(user_id: current_user.id, user_email: current_user.email) end end end ``` Event context is not automatically propagated to other threads. If you want to add context to events in a different thread, you can use the `Honeybadger.get_event_context` method to get the current context and pass it to the `Honeybadger.event` method: ```ruby class MyJob < ApplicationJob def perform(user_id) # Get context from the main thread context = Honeybadger.get_event_context Thread.new do # Set the context in the new thread Honeybadger.event_context(context) # Do some work here Honeybadger.event("background_work", { user_id: user_id, status: "completed" }) end end end ``` ## Block-scoped context [Section titled “Block-scoped context”](#block-scoped-context) You can also set event context for a specific block of code using a block form: ```ruby Honeybadger.event_context(user_id: 123) do # All events within this block will include the user_id context Honeybadger.event("user_action", { action: "login" }) Honeybadger.event("user_action", { action: "logout" }) end # Context is automatically cleared after the block ``` ## Clearing event context [Section titled “Clearing event context”](#clearing-event-context) You can clear the current event context at any time: ```ruby Honeybadger.event_context.clear! ``` # Filtering events > Ignore unwanted events before they're sent from your Ruby application to Honeybadger Insights. For some applications, certain default events may be unecessary or excessively data heavy. To specify events to ignore, use the `events.ignore` configuration option. Here you can specify a list of event types for the gem to ignore. They can be either a string or a regex. ```yaml events: ignore: - "enqueue.sidekiq" - !ruby/regexp "/.*.active_storage/" ``` You may also ignore events based on event data by specifying a hash object. ```yaml events: ignore: - event_type: "chatty_events" custom_data: "ignore_me" ``` This will ignore events that have been created with the matching `event_type` and key(symbol)/value: ```ruby Honeybadger.event('chatty_events', custom_data: 'ignore_me') # will not be sent to Insights ``` You can also use the `before_event` callback to inspect or modify event data, as well as calling `halt!` to prevent the event from being sent to Honeybadger: config/initializers/honeybadger.rb ```ruby Honeybadger.configure do |config| config.before_event do |event| # Ignore health check requests if event.event_type == "process_action.action_controller" && event[:controller] == "Rails::HealthController" event.halt! end # DB-backed job backends can generate a lot of useless queries if event.event_type == "sql.active_record" && event[:query].match?(/good_job|solid_queue/) event.halt! end end end ``` `before_event` can be called multiple times to add multiple callbacks. ## Default ignored events [Section titled “Default ignored events”](#default-ignored-events) The gem comes configured to ignore a few events that can be chatty and not useful: * `sql.active_record` events with queries that contain only “BEGIN” or “COMMIT”. * `sql.active_record` events for database backed background processing gems (SolidQueue and GoodJob). * `process_action.action_controller` events for `Rails::HealthController` actions. ## Sampling events [Section titled “Sampling events”](#sampling-events) If you’d rather reduce event volume across the board instead of ignoring specific events, see [Sampling events](/lib/ruby/insights/sampling-events/). # Sampling events > Send a percentage of events from your Ruby application to Honeybadger Insights to manage quota consumption. If you find that you’d like to report fewer events in order to minimize your quota consumption, you can conditionally send a certain percentage of events: config/honeybadger.yml ```yaml insights: sample_rate: 10 ``` This will send 10% of events not associated with a request, and all events for 10% of requests. To ignore specific events instead of sampling across the board, see [Filtering events](/lib/ruby/insights/filtering-events/). # Sending custom events > Send custom events from Ruby applications to Honeybadger Insights for monitoring and analysis. You can send your own application events to [Honeybadger Insights](/guides/insights/) using the `Honeybadger.event` method. (For the events the gem captures on its own — web requests, database queries, background jobs, and more — see [Automatic instrumentation](/lib/ruby/insights/automatic-instrumentation/).) ```ruby Honeybadger.event('user_activity', { action: 'registration', user_id: 123 }) ``` The first argument is the type of the event (`event_type`) and the second argument is an object containing any additional data you want to include. Payloads can include nested hashes and arrays, and are sanitized the same way error context is. `Honeybadger.event` can also be called with a single argument as an object containing the data for the event: ```ruby Honeybadger.event({ event_type: 'user_activity', action: 'registration', user_id: 123 }) ``` ## Naming events [Section titled “Naming events”](#naming-events) The `event_type` is how you’ll filter for these events in every query, so stable, descriptive names pay off. Dot-namespaced names group related events and read naturally in queries: `payment.completed`, `payment.refunded`, `export.finished`. The gem’s own events follow the same convention (`sql.active_record`, `perform.sidekiq`). ## Fields added automatically [Section titled “Fields added automatically”](#fields-added-automatically) The gem adds a few fields to every event before sending: | Field | Type | Description | | ------------- | ------------------ | -------------------------------------------------------------------------------------------------------------------------------------------- | | `ts` | string\ | Event timestamp (ISO 8601, UTC). Added unless you provide your own. | | `request_id` | string | Rails request ID, when the event is sent during a web request. Correlates your events with the gem’s automatic events from the same request. | | `hostname` | string | Server hostname. Disable with the `events.attach_hostname` [configuration option](/lib/ruby/gem-reference/configuration/). | | `environment` | string | Deploy environment. Disable with the `events.attach_environment` [configuration option](/lib/ruby/gem-reference/configuration/). | Fields set via [Event context](/lib/ruby/insights/event-context/) — user IDs, tenant IDs, and other per-request metadata — are also merged into every event. ## Delivery [Section titled “Delivery”](#delivery) `Honeybadger.event` doesn’t block: events are queued in memory and sent in batches — when 1,000 events accumulate or every 30 seconds, whichever comes first. The queue holds up to 100,000 events; batch size, timeout, and queue limits are [configurable](/lib/ruby/gem-reference/configuration/). When the process exits, the gem sends any remaining queued events (`send_data_at_exit`, on by default). For cases where you need delivery before continuing — a short-lived script that must not exit early, or work that follows immediately — `Honeybadger.flush` sends everything queued: ```ruby Honeybadger.flush do records.each { |r| Honeybadger.event("import.row_processed", id: r.id) } end ``` ## Finding your events [Section titled “Finding your events”](#finding-your-events) Filter by the `event_type` you chose: ```badgerql fields @ts, @preview | filter event_type::str == "user_activity" | filter action::str == "registration" | sort @ts ``` See the [BadgerQL guide](/guides/insights/badgerql/) for aggregations, grouping, and the rest of the query language. ## Managing event volume [Section titled “Managing event volume”](#managing-event-volume) If some events are noisy or you’d like to reduce quota consumption: * [Filtering events](/lib/ruby/insights/filtering-events/) — ignore specific event types, or inspect and halt events with a callback. * [Sampling events](/lib/ruby/insights/sampling-events/) — send only a percentage of events. # Tracking Ruby errors on AWS Lambda > Honeybadger monitors your Ruby AWS Lambda functions for errors and exceptions so that you can fix them wicked fast. **Typical installation time:** 1 minute Hi there! You’ve found Honeybadger’s guide to **Ruby Exception and error tracking on AWS Lambda and Serverless**. Once installed, Honeybadger will report exceptions wherever they may happen. If you’re new to Honeybadger, read our [Getting Started guide](/lib/ruby/) to become familiar with our Ruby gem. For a refresher on working with exceptions in Ruby, check out the [Honeybadger guide to Ruby exceptions](https://www.exceptionalcreatures.com/guides/what-are-ruby-exceptions/). ## Installation [Section titled “Installation”](#installation) The first step is to add the honeybadger gem to your Gemfile: ```ruby gem 'honeybadger' ``` Tell bundler to install: ```bash bundle install --deployment --without development,test ``` Depending on your deployment method, vendoring might be required to ensure your dependencies are included. We think the [serverless framework](https://serverless.com/framework/docs/providers/aws/examples/hello-world/ruby/) is a cool way to manage your lambda functions. It may help to use a Ruby version manager (something like [asdf](https://github.com/asdf-vm/asdf-ruby) or [rvm](https://rvm.io/)) to ensure you are building against your selected lambda Ruby runtime. You can view a list of lambda runtime versions [here](https://docs.aws.amazon.com/lambda/latest/dg/lambda-runtimes.html). You can configure Honeybadger in your Lambda by adding your API key via the `HONEYBADGER_API_KEY` environment variable. ## Capturing exceptions [Section titled “Capturing exceptions”](#capturing-exceptions) To automatically capture exceptions from your Lambda handler, register your handlers with the `hb_wrap_handler` method. Any unhandled exceptions raised within the specified methods will be automatically reported to Honeybadger. ```ruby require 'honeybadger' hb_wrap_handler :my_handler1, :my_handler2 def my_handler1(event:, context:) # ... end def my_handler2(event:, context:) # ... end ``` For class methods, you’ll need to first extend our `LambdaExtensions` module: ```ruby class MyLambdaApp extend ::Honeybadger::Plugins::LambdaExtension hb_wrap_handler :my_handler def self.my_handler(event:, context:) # ... end end ``` # Hanami integration guide > Honeybadger monitors your Hanami applications for errors and exceptions so that you can fix them wicked fast. **Typical installation time:** 4 minutes Hi there! You’ve found Honeybadger’s guide to **Hanami exception and error tracking**. Once installed, Honeybadger will automatically report exceptions wherever they may happen: * During a web request * In a background job * In a Rake task * When a process crashes (`at_exit`) If you’re new to Honeybadger, read our [Getting Started guide](/lib/ruby/index.html) to become familiar with our Ruby gem. For a refresher on working with exceptions in Ruby, check out the [Honeybadger guide to Ruby exceptions](https://www.exceptionalcreatures.com/guides/what-are-ruby-exceptions.html). ## Installation [Section titled “Installation”](#installation) The first step is to add the honeybadger gem to your Gemfile: ```ruby gem 'honeybadger' ``` Tell bundler to install: ```bash bundle install ``` Next, you'll set the API key for this project. ```bash bundle exec honeybadger install [Your project API key] ``` This will do three things: 1. Generate a `honeybadger.yml` file. If you don't like config files, you can place your API key in the `$HONEYBADGER_API_KEY` environment variable. 2. If Capistrano is installed, we'll add a require statement to *Capfile*. 3. Send a test exception to your Honeybadger project. Finally, require the honeybadger gem in your `config.ru`, before you run your Hanami app. config.ru ```ruby require "hanami/boot" require "honeybadger" run Hanami.app ``` If you’re on a Hanami **v1** app, you’ll need to add the Rack middleware manually: config.ru ```ruby require './config/environment' require 'honeybadger' # These two are optional (explained below), but for them # to work, they must be placed *before* the ErrorNotifier. use Honeybadger::Rack::UserInformer use Honeybadger::Rack::UserFeedback use Honeybadger::Rack::ErrorNotifier run Hanami.app ``` That’s it. Honeybadger will now automatically catch exceptions in your app. ## Identifying users [Section titled “Identifying users”](#identifying-users) If you’re using the *devise* or the *warden* gems for user authentication, then we already associate errors with the current user. For other authentication systems (or to customize the user values), use `Honeybadger.context` to associate the current user: ```ruby Honeybadger.context({ user_id: current_user.id, user_email: current_user.email }) ``` ## Collecting user feedback [Section titled “Collecting user feedback”](#collecting-user-feedback) The Honeybadger gem has a few special tags that it looks for whenever you render an error page in a Rack-based application. These can be used to display extra information about the error, or to ask the user for information about how they triggered the error. Honeybadger automatically installs the middleware for these in your Hanami project. ### Displaying the error ID [Section titled “Displaying the error ID”](#displaying-the-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 error pages. To include the error id, simply place this magic HTML comment on your error page (normally `public/500.html` in Rails): ```html ``` By default, we will replace this tag with: ```plaintext 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): config/honeybadger.yml ```yaml 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://app.honeybadger.io/notice/some-uuid-goes-here](https://app.honeybadger.io/notice/). ### Displaying a feedback form [Section titled “Displaying a feedback form”](#displaying-a-feedback-form) 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 (normally `public/500.html` in Rails): ```html ``` You can change the text displayed in the form via the Rails internationalization system. Here’s an example: config/locales/en.yml ```yaml 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)" ``` The feedback form can be enabled and disabled using the `feedback.enabled` config option (defaults to `true`): config/honeybadger.yml ```yaml feedback: enabled: true ``` # Heroku integration guide > Honeybadger monitors your Heroku Ruby applications for errors and exceptions so that you can fix them wicked fast. **Typical installation time:** 1 minute Hi there! You’ve found Honeybadger’s guide to **Ruby exception and error tracking on Heroku**. Once installed, Honeybadger will automatically report exceptions wherever they may happen: * During a web request * In a background job * In a rake task * When a process crashes (`at_exit`) If you’re new to Honeybadger, read our [Getting Started guide](/lib/ruby/) to become familiar with our Ruby gem. For a refresher on working with exceptions in Ruby, check out the [Honeybadger guide to Ruby exceptions](https://www.exceptionalcreatures.com/guides/what-are-ruby-exceptions/). ## Installation [Section titled “Installation”](#installation) The first step is to add the honeybadger gem to your Gemfile: ```ruby gem 'honeybadger' ``` Tell bundler to install: ```bash bundle install ``` You can configure Honeybadger on your dynos like so: *Note: This last step isn’t necessary if you’re using our [Heroku add-on](https://elements.heroku.com/addons/honeybadger), as it adds our API key to your Heroku config automatically.* ```bash 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. ### Tracking deployments [Section titled “Tracking deployments”](#tracking-deployments) To learn more about tracking deployments, see the [Tracking deployments](/lib/ruby/errors/tracking-deployments/) section of the [Getting Started guide](/lib/ruby/). Deploy tracking via Heroku is implemented using Heroku’s [app webhooks](https://devcenter.heroku.com/articles/app-webhooks). If you ran the [Installation](#installation) command already, then you should already have deployment tracking installed. Otherwise, to install the addon and configure it for Honeybadger, run the following CLI command from your project root: ```sh 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: ```sh heroku webhooks:add -i api:release -l notify -u "https://api.honeybadger.io/v1/deploys/heroku?repository=git@github.com/username/projectname&environment=production&api_key=asdf" --app app-name ``` You should replace the `repository`, `api_key`, and `app` options with your own values. You may also want to change the environment (set to production by default). For more about manual use of Heroku deploy tracking, see the [Heroku Deployments](/guides/heroku/#heroku-deployment-tracking) guide. # Rack integration guide > Honeybadger monitors your Ruby/Rack applications for errors and exceptions so that you can fix them wicked fast. **Typical installation time:** 4 minutes Hi there! You’ve found Honeybadger’s guide to **Rack exception and error tracking**. Once installed, Honeybadger will automatically report exceptions wherever they may happen: * During a web request * In a background job * In a rake task * When a process crashes (`at_exit`) If you’re new to Honeybadger, read our [Getting Started guide](/lib/ruby/index.html) to become familiar with our Ruby gem. For a refresher on working with exceptions in Ruby, check out the [Honeybadger guide to Ruby exceptions](https://www.exceptionalcreatures.com/guides/what-are-ruby-exceptions.html). ## Installation [Section titled “Installation”](#installation) The first step is to add the honeybadger gem to your Gemfile: ```ruby gem 'honeybadger' ``` Tell bundler to install: ```bash bundle install ``` Next, you'll set the API key for this project. ```bash bundle exec honeybadger install [Your project API key] ``` This will do three things: 1. Generate a `honeybadger.yml` file. If you don't like config files, you can place your API key in the `$HONEYBADGER_API_KEY` environment variable. 2. If Capistrano is installed, we'll add a require statement to *Capfile*. 3. Send a test exception to your Honeybadger project. Now it’s time to set up your Rack app. Start by requiring the *honeybadger* gem **after** any other gems you’re using: ```ruby require 'rack' # ... require 'honeybadger' ``` Then add the middleware to your app. Make sure Honeybadger’s middleware is the first middleware you define so that it can catch exceptions in your other middleware: ```ruby use Honeybadger::Rack::ErrorNotifier # ... ``` ### Example app [Section titled “Example app”](#example-app) ```ruby require 'rack' # Load the gem require 'honeybadger' # Write your app app = Rack::Builder.app do run lambda { |env| raise "Rack down" } end # These middleware are optional, but for them to work, # they must be placed *before* the ErrorNotifier middleware use Honeybadger::Rack::UserFeedback use Honeybadger::Rack::UserInformer # Use Honeybadger's Rack middleware use Honeybadger::Rack::ErrorNotifier # Use your other middleware here run app ``` ## Identifying users [Section titled “Identifying users”](#identifying-users) If you’re using the *devise* or the *warden* gems for user authentication, then we already associate errors with the current user. For other authentication systems (or to customize the user values), use `Honeybadger.context` to associate the current user: ```ruby Honeybadger.context({ user_id: current_user.id, user_email: current_user.email }) ``` ## Collecting user feedback [Section titled “Collecting user feedback”](#collecting-user-feedback) The Honeybadger gem has a few special tags that it looks for whenever you render an error page in a Rack-based application. These can be used to display extra information about the error, or to ask the user for information about how they triggered the error. You can enable them by adding the middleware to your application: ```ruby use Honeybadger::Rack::UserInformer use Honeybadger::Rack::UserFeedback # ^^^ These middleware must be placed *before* the ErrorNotifier use Honeybadger::Rack::ErrorNotifier ``` ### Displaying the error ID [Section titled “Displaying the error ID”](#displaying-the-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 error pages. To include the error id, simply place this magic HTML comment on your error page (normally `public/500.html` in Rails): ```html ``` By default, we will replace this tag with: ```plaintext 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): config/honeybadger.yml ```yaml 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://app.honeybadger.io/notice/some-uuid-goes-here](https://app.honeybadger.io/notice/). ### Displaying a feedback form [Section titled “Displaying a feedback form”](#displaying-a-feedback-form) 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 (normally `public/500.html` in Rails): ```html ``` You can change the text displayed in the form via the Rails internationalization system. Here’s an example: config/locales/en.yml ```yaml 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)" ``` The feedback form can be enabled and disabled using the `feedback.enabled` config option (defaults to `true`): config/honeybadger.yml ```yaml feedback: enabled: true ``` # Rails integration guide > Honeybadger monitors your Ruby on Rails applications for errors and exceptions so that you can fix them wicked fast. **Typical installation time:** 2 minutes Hi there! You’ve found Honeybadger’s guide to **Ruby on Rails exception and error tracking**. Once installed, Honeybadger will automatically report exceptions wherever they may happen: * During a web request * In a background job * In a rake task * When a process crashes (`at_exit`) If you’re new to Honeybadger, read our [Getting Started guide](/lib/ruby/index.html) to become familiar with our Ruby gem. For a refresher on working with exceptions in Ruby, check out the [Honeybadger guide to Ruby exceptions](https://www.exceptionalcreatures.com/guides/what-are-ruby-exceptions.html). ## Installation [Section titled “Installation”](#installation) [![Using the Honeybadger gem with Rails](https://embed-ssl.wistia.com/deliveries/e1e2133b8f1bec224c57f6677f6bdb11691b3822.jpg?image_play_button=true\&image_play_button_color=7b796ae0\&image_crop_resized=150x84)](https://honeybadger.wistia.com/medias/l3cmyucx8f) The first step is to add the honeybadger gem to your Gemfile: ```ruby gem 'honeybadger' ``` Tell bundler to install: ```bash bundle install ``` Next, you'll set the API key for this project. ```bash bundle exec honeybadger install [Your project API key] ``` This will do three things: 1. 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. 2. If Capistrano is installed, we'll add a require statement to *Capfile*. 3. Send a test exception to your Honeybadger project. Assuming the test completed successfully: **you’re done!** ## Identifying users [Section titled “Identifying users”](#identifying-users) If you’re using the *devise* or the *warden* gems for user authentication, then we already associate errors with the current user. For other authentication systems (or to customize the user values), add the following `before_action` to your `ApplicationController`: ```ruby before_action do Honeybadger.context({ user_id: current_user.id, user_email: current_user.email }) end ``` ## Collecting user feedback [Section titled “Collecting user feedback”](#collecting-user-feedback) 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 the error ID [Section titled “Displaying the error ID”](#displaying-the-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 error pages. To include the error id, simply place this magic HTML comment on your error page (normally `public/500.html` in Rails): ```html ``` By default, we will replace this tag with: ```plaintext 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): config/honeybadger.yml ```yaml 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://app.honeybadger.io/notice/some-uuid-goes-here](https://app.honeybadger.io/notice/). ### Displaying a feedback form [Section titled “Displaying a feedback form”](#displaying-a-feedback-form) 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 (normally `public/500.html` in Rails): ```html ``` You can change the text displayed in the form via the Rails internationalization system. Here’s an example: config/locales/en.yml ```yaml 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)" ``` The feedback form can be enabled and disabled using the `feedback.enabled` config option (defaults to `true`): config/honeybadger.yml ```yaml feedback: enabled: true ``` ## The Rails error reporter [Section titled “The Rails error reporter”](#the-rails-error-reporter) On Rails 7 and above, Honeybadger supports the new [error reporter](https://guides.rubyonrails.org/error_reporting.html) included in Rails. This means you can use `Rails.error.handle` as described in the Rails docs, and errors will be reported as normal, in line with your Honeybadger configuration. `Rails.error.record` is, however, not supported, since the Honeybadger native error handlers for each integration provide much richer context for your errors than Rails’ default. On Rails 7.1 and above, each error report can include a `source` parameter. You can use the Honeybadger config option `rails.subscriber_ignore_sources` to automatically ignore errors from certain sources: ```ruby Honeybadger.configure do |config| config.rails.subscriber_ignore_sources += [/some_source/] end ``` ## Content Security Policy reports [Section titled “Content Security Policy reports”](#content-security-policy-reports) You can use [Content Security Policy](https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP) headers to help mitigate XSS attacks, and Rails has a [DSL](https://guides.rubyonrails.org/security.html#content-security-policy) that you can use to configure those headers in your application. When a policy includes a `report-uri` or `report-to` directive, reports about blocked resources can be sent to a URL: ```ruby Rails.application.config.content_security_policy do |policy| policy.default_src :self, :https ... policy.report_uri -> { "https://api.honeybadger.io/v1/browser/csp?api_key=HB_API_KEY_GOES_HERE&report_only=true&env=#{Rails.env}&context[user_id]=#{respond_to?(:current_user) ? current_user&.id : nil}" } end ``` Every parameter in the URL is optional, aside from the `api_key` parameter. If you don’t need the value to be generated at request time (as in this example, to report the current user’s id), then you can provide a simple string as the argument to `report_uri`. If you set the `report_only` parameter to true, then our UI will label reports as “CSP Report”; otherwise, they will be labeled as “CSP Error”. CSP Reports and Errors show up with the rest of your app’s errors in the Honeybadger UI. For this reason, and since CSP reports can be very numerous, we recommend you create a separate Honeybadger project specifically for CSP reports. ## If you use `config.exceptions_app` [Section titled “If you use config.exceptions\_app”](#if-you-use-configexceptions_app) If you use [the `config.exceptions_app` Rails setting](https://guides.rubyonrails.org/configuring.html#rails-general-configuration) to display a custom error page, you may need some extra config for the correct controller and action name to be displayed in Honeybadger. The following snippet assumes that the name of your custom controller is “errors” (e.g. `ErrorsController`): ```ruby Honeybadger.configure do |config| config.before_notify do |notice| # Change "errors" to match your custom controller name. break if notice.component != "errors" # Look up original route path and override controller/action # in Honeybadger. params = Rails.application.routes.recognize_path(notice.url) notice.component = params[:controller] notice.action = params[:action] end end ``` ## JavaScript source maps with esbuild and Sprockets [Section titled “JavaScript source maps with esbuild and Sprockets”](#javascript-source-maps-with-esbuild-and-sprockets) If you’re using esbuild with Sprockets, you can generate source maps for your JavaScript assets and upload them to Honeybadger. This will allow Honeybadger to display the original source code for your minified JavaScript files. Here’s a [Rake Task](https://railsinspire.com/samples/18) that uploads source maps to Honeybadger via the `assets:precompile` step. # Ruby integration guide > Honeybadger monitors your Ruby applications for errors and exceptions so that you can fix them wicked fast. **Typical installation time:** 3 minutes Hi there! You’ve found Honeybadger’s guide to **Ruby exception and error tracking**. Once installed, Honeybadger will automatically report exceptions wherever they may happen: * During a web request * In a background job * In a rake task * When a process crashes (`at_exit`) If you’re new to Honeybadger, read our [Getting Started guide](/lib/ruby/) to become familiar with our Ruby gem. For a refresher on working with exceptions in Ruby, check out the [Honeybadger guide to Ruby exceptions](https://www.exceptionalcreatures.com/guides/what-are-ruby-exceptions.html). ## Installation [Section titled “Installation”](#installation) The first step is to add the honeybadger gem to your Gemfile: ```ruby gem 'honeybadger' ``` Tell bundler to install: ```bash bundle install ``` Next, you'll set the API key for this project. ```bash bundle exec honeybadger install [Your project API key] ``` This will do three things: 1. Generate a `honeybadger.yml` file. If you don't like config files, you can place your API key in the `$HONEYBADGER_API_KEY` environment variable. 2. If Capistrano is installed, we'll add a require statement to *Capfile*. 3. Send a test exception to your Honeybadger project. Next, require the *honeybadger* gem **after** any other gems you’re using: ```ruby # ... require 'honeybadger' ``` Honeybadger will detect any supported 3rd-party gems you’re using such as Sidekiq, Rake, etc. and integrate with them automatically. To notify Honeybadger of an exception you’ve rescued, use `Honeybadger.notify`: ```ruby begin fail 'oops' rescue => exception Honeybadger.notify(exception) end ``` For additional ways to use `Honeybadger.notify`, check out the [Reporting errors](/lib/ruby/errors/reporting-errors/) chapter of our [Getting started guide](/lib/ruby/). For Rack-based web applications, see the [Rack integration guide](/lib/ruby/integration-guides/rack-exception-tracking/) for instructions on how to automatically report exceptions in web requests. # Sinatra integration guide > Honeybadger monitors your Sinatra applications for errors and exceptions so that you can fix them wicked fast. **Typical installation time:** 3 minutes Hi there! You’ve found Honeybadger’s guide to **Sinatra exception and error tracking**. Once installed, Honeybadger will automatically report exceptions wherever they may happen: * During a web request * In a background job * In a Rake task * When a process crashes (`at_exit`) If you’re new to Honeybadger, read our [Getting Started guide](/lib/ruby/index.html) to become familiar with our Ruby gem. For a refresher on working with exceptions in Ruby, check out the [Honeybadger guide to Ruby exceptions](https://www.exceptionalcreatures.com/guides/what-are-ruby-exceptions.html). ## Installation [Section titled “Installation”](#installation) [![Using the Honeybadger gem with Sinatra](https://embed-ssl.wistia.com/deliveries/7c9b6e6831f2288874f24d10eec88116e9f378eb.jpg?image_play_button=true\&image_play_button_color=7b796ae0\&image_crop_resized=150x84)](https://honeybadger.wistia.com/medias/b2wr5n9fcv) The first step is to add the honeybadger gem to your Gemfile: ```ruby gem 'honeybadger' ``` Tell bundler to install: ```bash bundle install ``` Next, you'll set the API key for this project. ```bash bundle exec honeybadger install [Your project API key] ``` This will do three things: 1. Generate a `honeybadger.yml` file. If you don't like config files, you can place your API key in the `$HONEYBADGER_API_KEY` environment variable. 2. If Capistrano is installed, we'll add a require statement to *Capfile*. 3. Send a test exception to your Honeybadger project. Finally, require the honeybadger gem in your app *after* requiring the sinatra gem: ```ruby # 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 ``` ## Identifying users [Section titled “Identifying users”](#identifying-users) If you’re using the *devise* or the *warden* gems for user authentication, then we already associate errors with the current user. For other authentication systems (or to customize the user values), use `Honeybadger.context` to associate the current user: ```ruby Honeybadger.context({ user_id: current_user.id, user_email: current_user.email }) ``` ## Collecting user feedback [Section titled “Collecting user feedback”](#collecting-user-feedback) The Honeybadger gem has a few special tags that it looks for whenever you render an error page in a Rack-based application. These can be used to display extra information about the error, or to ask the user for information about how they triggered the error. Honeybadger automatically installs the middleware for these in your Sinatra project. ### Displaying the error ID [Section titled “Displaying the error ID”](#displaying-the-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 error pages. To include the error id, simply place this magic HTML comment on your error page (normally `public/500.html` in Rails): ```html ``` By default, we will replace this tag with: ```plaintext 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): config/honeybadger.yml ```yaml 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://app.honeybadger.io/notice/some-uuid-goes-here](https://app.honeybadger.io/notice/). ### Displaying a feedback form [Section titled “Displaying a feedback form”](#displaying-a-feedback-form) 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 (normally `public/500.html` in Rails): ```html ``` You can change the text displayed in the form via the Rails internationalization system. Here’s an example: config/locales/en.yml ```yaml 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)" ``` The feedback form can be enabled and disabled using the `feedback.enabled` config option (defaults to `true`): config/honeybadger.yml ```yaml feedback: enabled: true ``` ## Content Security Policy reports [Section titled “Content Security Policy reports”](#content-security-policy-reports) You can use [Content Security Policy](https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP) headers to help mitigate XSS attacks, and the [SecureHeaders](https://rubygems.org/gems/secure_headers) gem makes it easy to emit those headers from your Sinatra application. When a policy includes a `report-uri` or `report-to` directive, reports about blocked resources can be sent to a URL: ```ruby require 'rubygems' require 'sinatra' require 'secure_headers' use SecureHeaders::Middleware SecureHeaders::Configuration.default do |config| ... report_uri: "https://api.honeybadger.io/v1/browser/csp?api_key=HB_API_KEY_GOES_HERE&report_only=true&env=#{ENV['RACK_ENV']}" end ``` Every parameter in the URL is optional, aside from the `api_key` parameter. If you don’t need the value to be generated at request time (as in this example, to report the current user’s id), then you can provide a simple string as the argument to `report_uri`. If you set the `report_only` parameter to true, then our UI will label reports as “CSP Report”; otherwise, they will be labeled as “CSP Error”. CSP Reports and Errors show up with the rest of your app’s errors in the Honeybadger UI. For this reason, and since CSP reports can be very numerous, we recommend you create a separate Honeybadger project specifically for CSP reports. # Architecture deep-dive > Learn about Honeybadger's Ruby gem architecture, threading model, and how error reporting works internally. This guide explains the architecture of the [*honeybadger* Ruby gem](https://github.com/honeybadger-io/honeybadger-ruby), and how it interacts with your application. ## Who is this guide for? [Section titled “Who is this guide for?”](#who-is-this-guide-for) This guide is for anyone interested in learning about how our gem works internally or is attempting to debug/rule out a gem-related issue. ## The major components of the gem [Section titled “The major components of the gem”](#the-major-components-of-the-gem) The `honeybadger` gem has the following components: * `Notice` — Represents a single exception/error report * `Backend` — Responsible for reporting a `Notice` to the honeybadger.io API * `Queue` — A first-in-first-out (FIFO) queue which drops items after reaching a maximum size * `Worker` — A single-threaded worker that is responsible for processing `Notice` items in the `Queue` and notifying the `Backend` * `Initializer` — An integration with a detected framework (such as Rails) * `Plugin` — An isolated integration with a Ruby or 3rd party gem feature * `Config` — The user [configuration](/lib/ruby/gem-reference/configuration/) for the gem * `Agent` — An instance of the gem composed of a `Config` and a `Worker` (multiple `Agents` are supported, but are uncommon) * `Honeybadger` — The global singleton `Agent` ## What happens when your app boots [Section titled “What happens when your app boots”](#what-happens-when-your-app-boots) The gem has two modes of booting: 1. **Normal mode**: loads `Initializers`, `Config`, and `Plugins` automatically (this is what we’ll be discussing here) 2. [Plain Ruby Mode](/lib/ruby/getting-started/plain-ruby-mode/): Skips automatically loading `Initializers`, `Config`, and `Plugins` If your app is configured to `require 'honeybadger'` (the default when you install our gem), then it boots in **Normal Mode**. Here is the order of events in a Rails app: 1. When `'honeybadger'` is required, we immediately: 2. Detect your framework (Rails, Sinatra, etc.) and load the respective `Initializer` 3. Load our Rake `Initializer` if Rake is present in your application 4. Install our global `at_exit` handler 5. As Rails initializes, our Rack middleware are inserted in the Rails middleware stack via the `honeybadger.install_middleware` initializer (see our [Railtie](https://github.com/honeybadger-io/honeybadger-ruby/blob/master/lib/honeybadger/init/rails.rb)) 6. Rails finishes initializing 7. Honeybadger reads `Config` from supported sources 8. Honeybadger loads `Plugins` 9. Rails finishes booting ## The life cycle of an exception [Section titled “The life cycle of an exception”](#the-life-cycle-of-an-exception) The *honeybadger* gem integrates with popular frameworks and libraries to automatically report exceptions when they occur. Examples of where this can happen: * Rails and Sinatra requests * Background jobs (ActiveJob, Sidekiq, Resque, etc.) * Rake tasks * Ruby crashes (via our global `at_exit` handler) Here is the order of events when an unhandled exception occurs in one of these scenarios: 1. The exception is reported to the global singleton `Agent` using [`Honeybadger.notify`](https://www.rubydoc.info/gems/honeybadger/Honeybadger/Agent#notify-instance_method) 2. A `Notice` is built from the exception and any other data passed to `Honeybadger.notify`, `Honeybadger.context`, `Honeybadger.add_breadcrumb`, etc. 3. Configured [`before_notify` callbacks](/lib/ruby/gem-reference/configuration/#changing-notice-data) are executed, passing the `Notice` to each callback (which may modify it) 4. If the `Notice` is ignored via `Config`, `before_notify` callbacks, etc., then it’s immediately dropped. Otherwise, it’s pushed to the `Worker`. 5. The `Worker` processes each `Notice` in the order that it was added to its `Queue`. The `Queue` holds up to 100 `Notices` by default (this number is configurable via the [`max_queue_size` option](/lib/ruby/gem-reference/configuration/#configuration-options)). If the number of `Notices` in the `Queue` equals the `max_queue_size`, new `Notices` are dropped until the number is reduced. 6. When the `Worker` processes a notice, it removes it from the `Queue`, passes it to the `Backend`, and waits for a response from the honeybadger.io API: 1. `429`, `503` (throttled): Applies an exponential throttle of `1.05`. When a throttle is added, the `Worker` will briefly pause between processing each `Notice` in the `Queue`. Additional throttles are added until the server stops throttling the client. Each new throttle multiplies the previous throttle by `1.05`; for example, three `429` responses would result in a \~0.158-second pause (`((1.05*1.05*1.05)-1)`—we subtract 1 to account for the initial throttle). 2. `402`, `403` (payment required/invalid API key): Suspends the `Worker` for 1 hour. During this time, all `Notices` are dropped. 3. `201` (success): if throttled, one throttle per `201` response is removed until the `Worker` is back to processing the `Queue` in real-time. ## What happens when your app shuts down [Section titled “What happens when your app shuts down”](#what-happens-when-your-app-shuts-down) Honeybadger performs the following via our global `at_exit` handler: 1. If there is an exception that is crashing the Ruby process, it’s reported to `Honeybadger.notify`, which calls the backend synchronously (it skips the `Worker`) 2. The `Worker` shuts down. By default, it will wait to process remaining exceptions in the `Queue`. [See `send_data_at_exit` and `max_queue_size`](/lib/ruby/gem-reference/configuration/#configuration-options) # Frequently asked questions > Find answers to frequently asked questions about Honeybadger's Ruby gem for error tracking and application monitoring. ## Why aren’t my errors being reported? [Section titled “Why aren’t my errors being reported?”](#why-arent-my-errors-being-reported) The most common reason for errors not being reported is that the gem is in a development environment. See the [Environments](/lib/ruby/errors/environments/#development-environments) chapter in the **Getting Started** guide for more information. The second most common reason is that the error being reported is on the [default ignored exceptions list](/lib/ruby/errors/ignoring-errors/#ignore-by-class). We also don’t capture errors in a Ruby console (IRB, pry, etc..) by default, even in production. If neither of these is the issue, check out the [Troubleshooting guide](/lib/ruby/support/troubleshooting/#my-errors-arent-being-reported). ## Why aren’t I getting notifications? [Section titled “Why aren’t I getting notifications?”](#why-arent-i-getting-notifications) By default we only send notifications the first time an exception happens, and when it re-occurs after being marked resolved. If an exception happens 100 times, but was never resolved you’ll only get 1 email about it. ## Can I use Honeybadger outside of Rails, such as in my gem? [Section titled “Can I use Honeybadger outside of Rails, such as in my gem?”](#can-i-use-honeybadger-outside-of-rails-such-as-in-my-gem) Yes! All our gem needs to report errors is a supported Ruby version; there are no other hard dependencies. We detect and integrate with optional dependencies such as Rails by default, but if you want complete control of the initialization process you can use [Plain Ruby Mode](/lib/ruby/getting-started/plain-ruby-mode/). See the [API Reference](https://www.rubydoc.info/gems/honeybadger/Honeybadger/Agent) for all the methods you can use to report errors from anywhere in Ruby. ## After enabling Insights, I see a lot of extra console output during my builds. How can I silence this? [Section titled “After enabling Insights, I see a lot of extra console output during my builds. How can I silence this?”](#after-enabling-insights-i-see-a-lot-of-extra-console-output-during-my-builds-how-can-i-silence-this) If you enabled Insights via your `config/honeybadger.yml` file, you may see extra output in your console during builds (such as asset compile in Docker). This is because the Honeybadger Insights agent is running as configured. You can temporarily disable Insights during your builds by setting the `HONEYBADGER_INSIGHTS_ENABLED` environment variable to `false`. ```bash HONEYBADGER_INSIGHTS_ENABLED=false bundle exec rake assets:precompile ``` Alternatively, instead of configuring Insights in your `config/honeybadger.yml` file, you can enable it via the `HONEYBADGER_INSIGHTS_ENABLED` environment variable in your proudction environment. This way, Insights will only be enabled in production. # Troubleshooting > Troubleshoot common issues with Honeybadger's Ruby gem and resolve integration problems. Common issues/workarounds are documented here. If you don’t find a solution to your problem here or in our [support documentation](../../#getting-support), email and we’ll assist you! ## Upgrade the gem [Section titled “Upgrade the gem”](#upgrade-the-gem) Before digging deeper into this guide, **make sure you are on the latest minor release of the honeybadger gem** (i.e. 3.x.x). There’s a chance you’ve found a bug which has already been fixed! ## Send a test exception [Section titled “Send a test exception”](#send-a-test-exception) You can send a test exception using the `honeybadger` command line utility: ```bash honeybadger test ``` ## How to enable verbose logging [Section titled “How to enable verbose logging”](#how-to-enable-verbose-logging) Troubleshooting any of these issues will be much easier if you can see what’s going on with Honeybadger when your app starts. To enable verbose debug logging, run your app with the `HONEYBADGER_DEBUG=true` environment variable or add the following to your *honeybadger.yml* file: ```yaml debug: true ``` By default Honeybadger will log to the default Rails logger or STDOUT outside of Rails. When debugging it can be helpful to have a dedicated log file for Honeybadger. To enable one, set the `HONEYBADGER_LOGGING_PATH=log/honeybadger.log` environment variable or add the following to your *honeybadger.yml* file: ```yaml logging: path: "log/honeybadger.log" ``` ## Common issues [Section titled “Common issues”](#common-issues) ### My errors aren’t being reported [Section titled “My errors aren’t being reported”](#my-errors-arent-being-reported) Error reporting may be disabled for several reasons: #### Honeybadger is not configured [Section titled “Honeybadger is not configured”](#honeybadger-is-not-configured) Honeybadger requires at minimum the `api_key` option to be set. If Honeybadger is unable to start due to invalid configuration, you should see something like the following in your logs: ```plaintext ** [Honeybadger] Unable to start Honeybadger -- api_key is missing or invalid. level=2 pid=18195 ``` #### Honeybadger is in a development environment [Section titled “Honeybadger is in a development environment”](#honeybadger-is-in-a-development-environment) Errors are ignored by default in the “test”, “development”, and “cucumber” environments. To explicitly enable Honeybadger in a development environment, set the `HONEYBADGER_REPORT_DATA=true` environment variable or add the following configuration to *honeybadger.yml* file (change “development” to the name of the environment you want to enable): ```yaml development: report_data: true ``` #### The error is ignored by default [Section titled “The error is ignored by default”](#the-error-is-ignored-by-default) Honeybadger ignores [this list of exceptions](https://github.com/honeybadger-io/honeybadger-ruby/blob/master/lib/honeybadger/config/defaults.rb#L7) by default. #### The error was rescued without re-raising [Section titled “The error was rescued without re-raising”](#the-error-was-rescued-without-re-raising) Honeybadger will automatically report exceptions in many frameworks including Rails, Sinatra, Sidekiq, Rake, etc. For exceptions to reported automatically they must be raised; check for any `rescue` statements in your app where exceptions may be potentially silenced. In Rails, this includes any use of `rescue_from` which does not re-raise the exception. Errors which are handled in a `rescue` block without re-raising must be reported to Honeybadger manually: ```ruby begin fail 'This error will be handled internally.' rescue => e Honeybadger.notify(e) end ``` #### The configuration is being overridden [Section titled “The configuration is being overridden”](#the-configuration-is-being-overridden) Check to make sure that you aren’t overriding the *honeybadger.yml* configuration file via Ruby configuration using `Honeybadger.configure`, or using an environment variable (`HONEYBADGER_API_KEY`, for instance). For example, the Honeybadger Heroku addon sets the `HONEYBADGER_API_KEY` config option automatically, so you must remove the addon (or the config option) if you switch to a Honeybadger project with a different API key. #### A rake task is running in a local terminal [Section titled “A rake task is running in a local terminal”](#a-rake-task-is-running-in-a-local-terminal) By default, the Honeybadger rake integration reports errors that happen when running *outside* of a terminal, such as in a cron job or scheduled task. The integration does *not* report errors which happen when running rake manually from a terminal (i.e., if you SSH into a production server to run the task). [To report exceptions all the time, set the `exceptions.rescue_rake` config option to `true`](/lib/ruby/gem-reference/configuration/#configuration-options). #### The `better_errors` gem is installed [Section titled “The better\_errors gem is installed”](#the-better_errors-gem-is-installed) The [`better_errors` gem](https://github.com/charliesome/better_errors) conflicts with the Honeybadger gem when in development mode. To be able to report errors from development you must first temporarily disable/remove the `better_errors` gem. Better Errors should not affect production because it should never be enabled in production. ### I’m not receiving notifications [Section titled “I’m not receiving notifications”](#im-not-receiving-notifications) Likewise, if the error is reported but your aren’t being notified: #### The error was reported already and is unresolved [Section titled “The error was reported already and is unresolved”](#the-error-was-reported-already-and-is-unresolved) By default we only send notifications the first time an exception happens, and when it re-occurs after being marked resolved. If an exception happens 100 times, but was never resolved you’ll only get 1 email about it. ### `SignalException` or `SystemExit` is reported when a process or rake task exits [Section titled “SignalException or SystemExit is reported when a process or rake task exits”](#signalexception-or-systemexit-is-reported-when-a-process-or-rake-task-exits) The Honeybadger gem currently [ignores signal exceptions](https://github.com/honeybadger-io/honeybadger-ruby/blob/v4.2.1/lib/honeybadger/singleton.rb#L91) in our `at_exit` callback, which is installed by default whenever Honeybadger is loaded. We do not ignore these exceptions anywhere else, such as in Rake tasks. If you would like to ignore them globally, you can add the following configuration to `honeybadger.yml`: ```yaml exceptions: ignore: - !ruby/class "SystemExit" - !ruby/class "SignalException" ``` * Related: [#306](https://github.com/honeybadger-io/honeybadger-ruby/issues/306) ## Sidekiq/Resque/ActiveJob/etc. [Section titled “Sidekiq/Resque/ActiveJob/etc.”](#sidekiqresqueactivejobetc) * See [Common Issues](#common-issues) ### If the error is ignored by default [Section titled “If the error is ignored by default”](#if-the-error-is-ignored-by-default) Honeybadger ignores [this list of exceptions](https://github.com/honeybadger-io/honeybadger-ruby/blob/master/lib/honeybadger/config/defaults.rb#L7) by default. It may be surprising that `ActiveRecord::RecordNotFound` is on that list; that’s because in a Rails controller that error class is treated as a 404 not-found and handled internally (and thus we shouldn’t report it). Support for Sidekiq and friends was added later and inherited the default. We would like to provide alternate defaults for job processors in the future, but for now you can provide your own list of ignored class names if you want to change this behavior: ```plaintext HONEYBADGER_EXCEPTIONS_IGNORE_ONLY=Error,ClassNames,Here bundle exec sidekiq ``` ## Command line utility [Section titled “Command line utility”](#command-line-utility) If you get an error while running the `honeybadger` command line utility: 1. Try prefixing the command with `bundle exec`…even if you normally rely on bin-stubs to do this for you 2. Check `honeybadger help` if you’re having trouble with the syntax for a specific command. 3. Try enabling [verbose logging](#how-to-enable-verbose-logging) to get more info 4. Ask Us! We’re always here to help. Just copy the terminal output and email it to us at ## Wrong controller/action name is reported in Rails [Section titled “Wrong controller/action name is reported in Rails”](#wrong-controlleraction-name-is-reported-in-rails) If you’re using `config.exceptions_app`, you may need some extra config to report the correct controller and action to Honeybadger. See the [Rails integration guide](/lib/ruby/integration-guides/rails-exception-tracking/#if-you-use-configexceptions_app). * Related: [#250](https://github.com/honeybadger-io/honeybadger-ruby/issues/250#issuecomment-379780492) ## My issue isn’t here [Section titled “My issue isn’t here”](#my-issue-isnt-here) For a deep-dive into how the [*honeybadger* gem](https://github.com/honeybadger-io/honeybadger-ruby/) works, check out the [Architecture Guide](/lib/ruby/support/architecture/). If you’re stuck, shoot us an: