Created
September 1, 2022 17:34
-
-
Save darrenclark/971770561cc125e328decadabba8f817 to your computer and use it in GitHub Desktop.
BugsnagLoggerBackend
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule BugsnagLoggerBackend do | |
@behaviour :gen_event | |
@impl true | |
def init(__MODULE__) do | |
{:ok, %{}} | |
end | |
@impl true | |
def handle_call({:configure, _options}, state) do | |
{:ok, :ok, state} | |
end | |
@impl true | |
def handle_event({_level, gl, {Logger, _, _, _}}, state) | |
when node(gl) != node() do | |
{:ok, state} | |
end | |
def handle_event({:error, _gl, {Logger, _msg, _ts, md}}, state) do | |
if Keyword.has_key?(md, :crash_reason) do | |
report_crash(md) | |
end | |
{:ok, state} | |
end | |
def handle_event({_level, _gl, {Logger, _msg, _ts, _md}}, state) do | |
{:ok, state} | |
end | |
def handle_event(:flush, state) do | |
{:ok, state} | |
end | |
def handle_event(_, state) do | |
{:ok, state} | |
end | |
@impl true | |
def handle_info(_, state) do | |
{:ok, state} | |
end | |
@impl true | |
def code_change(_old_vsn, state, _extra) do | |
{:ok, state} | |
end | |
@impl true | |
def terminate(_reason, _state) do | |
:ok | |
end | |
defp report_crash(metadata) do | |
{raw_error, stacktrace} = Keyword.fetch!(metadata, :crash_reason) | |
error = normalize_error(raw_error) | |
Bugsnag.report(error, stacktrace: stacktrace) | |
end | |
defp error_kind(%{__exception__: _}), do: :error | |
defp error_kind({:nocatch, _}), do: :throw | |
defp error_kind(_), do: :exit | |
defp error_reason({:nocatch, reason}), do: reason | |
defp error_reason(reason), do: reason | |
defp normalize_error(%{__exception__: _} = error), do: error | |
defp normalize_error(error) do | |
kind = error_kind(error) | |
reason = error_reason(error) | |
# throws & exits look better when formatted as RuntimeError, the | |
# Bugsnag reporter doesn't handle formatting erlang errors well | |
%RuntimeError{ | |
message: Exception.format_banner(kind, reason) | |
} | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment