Introducing Honeybadger for Crystal

We are excited that you can now easily plug your Crystal applications into Honeybadger. Installation and configuration are easy, and the shard provides everything you need to set up your application. In this article, we'll cover installing Honeybadger, capturing errors in HTTP servers, manually capturing errors, and collecting context data from the Crystal Log::Context. Installing […]

We are excited that you can now easily plug your Crystal applications into Honeybadger. Installation and configuration are easy, and the shard provides everything you need to set up your application.

In this article, we'll cover installing Honeybadger, capturing errors in HTTP servers, manually capturing errors, and collecting context data from the Crystal Log::Context.

Installing

Update your shard.yml with the following snippet and shards install

dependencies:
+  honeybadger:
+    github: honeybadger-io/honeybadger-crystal

Provide your Honeybadger API key at runtime

Visit your Project Settings page on Honeybadger and find your API key. Add the following code to your application startup, and configure your API key in the environment:

Honeybadger.configure do |config|
  config.api_key = ENV["HONEYBADGER_API_KEY"]? || "API Key"
  config.environment = ENV["HONEYBADGER_ENVIRONMENT"]? || "production"
end

Capturing exceptions — HTTP::Server

For HTTP frameworks based on Crystal’s excellent HTTP::Server library, add the Honeybadger::Handler middleware to the server stack:

require "http/server"
require "honeybadger"

server = HTTP::Server.new([
  Honeybadger::Handler.new, # added at the top of the stack
  HTTP::LogHandler.new,
  HTTP::CompressHandler.new,
  HTTP::StaticFileHandler.new("."),
])

server.bind_tcp "127.0.0.1", 8080
server.listen

Adding Honeybadger::Handler to the top of the server stack allows it to capture and report as many errors as possible. Any exception raised within the server stack will be captured and reported to the Honeybadger API.

Capturing exceptions — General utility

For applications which don't leverage HTTP::Server, an application-wide capture is still helpful and might look something like this:

require "honeybadger"

def run_application
  do_work
  send_messages
rescue exception : Exception
    Honeybadger.notify exception
end

run_application

Log context

Crystal’s unique and powerful Log::Context system allows easily decorating log entries with helpful information like this:

user = Users.first
Log.context.set user_id: user.id
user.send_email!
Log.info { "Sent email to User##{user.id}" }

Out of the box, Honeybadger includes the current Log::Context with exceptions reported via Honeybadger.notify — it's dead simple!

Source: Honeybadger