Exception Monitoring for Elixir Phoenix with Sentry

We will show you how to set up exception monitoring for Elixir Phoenix with Sentry. Once you have deployed your Phoenix app to production, next you want to set up exception monitoring. When you enable exception monitoring with Sentry, it instantly notifies you when a user experiences any errors within your Phoenix application. Sentry was awarded Best Combination of Error and Performance Monitoring in our article covering the Best Error Monitoring Services for Elixir and Phoenix.

You will start by signing up for a free trial, create a new Phoenix application, then set up the exception monitoring tool, and finally test notifications in development on your local machine.

Overview

Here are the steps we’ll cover to set up and test Elixir exception monitoring with Sentry.

  1. Sign Up for Sentry
  2. Create New Elixir Phoenix App
  3. Add Sentry config
  4. Add Error to Phoenix Homepage

Prerequisites

To follow this guide, make sure you have at least the following applications installed on your machine. In the brackets are the versions with which this guide was written.

  • Elixir (1.12.3-otp-24)
  • Erlang (OTP 24.1)
  • Phoenix (1.6.2)
  • Node.js with npm (15.14.0)

If you run into problems, the finished project is available on GitHub as StakNine HelloSentry.

Sign Up for Sentry

Before we get started with the Phoenix app, you need to sign up for a free trial with Sentry. We’ll use the trial period to see how it works.

Sign Up for Free Trial

Now that you have an account, Sentry will guide your through the setup process. There are a number of devops tools and supported languages. We intend to set up the exception monitoring tool in this guide. Select Elixir for your programming language.

Exception Monitoring for Elixir Phoenix with Sentry

Next we need to create a new Phoenix app.

Create new Elixir Phoenix App

We are going to create a simple Phoenix project called HelloSentry. Use the command line to update your Phoenix version and create a new Phoenix application.

$ mix archive.install hex phx_new 1.6.2
$ mix phx.new hello_sentry

Change into the project directory, create your database and start your server.

$ cd hello_sentry
$ mix ecto.create
$ mix phx.server

Now visit http://localhost:4000 and you should see the Welcome to Phoenix! page.

phoenix homepage

Add Sentry config

We need to make a few updates to our app source code to configure it to start monitoring for errors and sending exceptions to Sentry. If you run into issues, check out the GitHub page for the Sentry Client for Elixir.

Install package

Edit your mix.exs file to add the Sentry package in your application and run mix do deps.get, deps.compile. Sentry does not install a JSON library nor HTTP client by itself. Sentry will default to trying to use Jason for JSON operations and Hackney for HTTP requests. Jason is already installed in our version of Phoenix (v1.6.2).

defp deps do
  [
    # ...
    {:sentry, "~> 8.0"},
    {:hackney, "~> 1.8"},
  ]
end

Once you edit your mix.exs file, we’ll finish config for the sentry package.

Configure Sentry

Sentry has a range of configuration options, but we will configure our app with the following:

config :sentry,
  dsn: "https://[email protected]/1",
  environment_name: Mix.env(),
  enable_source_code_context: true,
  root_source_code_path: File.cwd!(),
  tags: %{
    env: Mix.env()
  },
  included_environments: [:dev, :prod]

NOTE: The Sentry onboarding documentation will provide you the dsn link.

The environment_name and included_environments work together to determine if and when Sentry should send events to the server. If the currently configured :environment_name is in the configured list of :included_environments, the event will be sent.

We’ll use environment_name: Mix.env() to get the current environment.

Normally, you would only include :prod in your list of included_environments. However, we plan to test in development and we will remove it once we see how it works.

Set up exception monitoring and error reporting for Phoenix

Capturing errors in Phoenix applications is done with Sentry.PlugContext and Sentry.PlugCapture. Sentry.PlugContext adds contextual metadata from the current request which is then included in errors that are captured and reported by Sentry.PlugCapture.

First add use Sentry.PlugCapture above the use Phoenix.Endpoint line in your endpoint file. Then add Sentry.PlugContext below Plug.Parsers.

 defmodule HelloSentryWeb.Endpoint
   #Add the following line
   use Sentry.PlugCapture
   use Phoenix.Endpoint, otp_app: :my_app
   # ...
   plug Plug.Parsers,
     parsers: [:urlencoded, :multipart, :json],
     pass: ["*/*"],
     json_decoder: Phoenix.json_library()

   #Add the following line
   plug Sentry.PlugContext

Now that we have configured our project to capture exceptions, we’ll create an error to test our setup.

Add error to Phoenix homepage

Before we can test reporting Elixir errors, we need to create them. If we want to specify the type and message, we need to use raise/2.

Lets add this to our lib/hello_sentry_web/controllers/page_controller.ex.

defmodule HelloSentryWeb.PageController do
  use HelloSentryWeb, :controller

  def index(conn, _params) do
    raise ArgumentError, message: "We are testing error reporting with Sentry"
    render(conn, "index.html")
  end
end

Test Error Reporting and Notifications

Finally, we’re going to see how Sentry notifies developers when errors occur in your web service.

We’ve added an error to the homepage controller, so we will see errors when we start the server and visit the homepage.

$ mix phx.server

Now visit http://localhost:4000 and you should see the following screen in your browser.

Error in Phoenix Homepage

Now at the end of your onboarding steps, you will receive a notice, Event was received!. Next click Take me to my error to see the error details.

sentry event received

Sentry will provide error details including the error message and stacktrace. While the error is Unresolved, you will not receive additional notifications for this specific isssue.

Sentry Error Details

If you click on Issues in the sidebar, you will see the list errors for your application.

Sentry issue list

You can add more notification channels in the settings. For example, you could notify other developers in your company using your project management tools.

Sentry integrations

Now that we’ve seen how exception notifications work, you can remove the error from the PageController and remove :dev we added for included_environments in our config/config.exs:

included_environments: [:prod]

Then mark the error as Resolved in your dashboard.

Resolved Sentry Error Exception for Elixir Phoenix

Conclusion

Congratulations! You set up exception monitoring for Elixir Phoenix using Sentry. It is a good tool to notify you and other developers on your team or company when there are exceptions in you system. Once you have this set up, check out their other developer tools with features like performance monitoring and release tracking.

Want To Know How To Deploy Phoenix Apps Using A single Command?

This brand-new FREE training reveals the most powerful new way to reduce your deployment time and skyrocket your productivity… and truly see your programming career explode off the charts!