Skip to content

Commit

Permalink
Rework stop event and re-add original event
Browse files Browse the repository at this point in the history
  • Loading branch information
Bryan Naegele committed Oct 16, 2019
1 parent c1e01c1 commit 4b961cc
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 37 deletions.
77 changes: 41 additions & 36 deletions lib/tesla/middleware/telemetry.ex
Original file line number Diff line number Diff line change
Expand Up @@ -45,56 +45,61 @@ if Code.ensure_loaded?(:telemetry) do
"""

@doc false
def call(req_env, next, opts) do
def call(env, next, opts) do
prefix = Keyword.get(opts, :event_prefix, [])
start_time = System.monotonic_time()

try do
emit_start(req_env, start_time, prefix)
emit_start(env, start_time, prefix)

Tesla.run(req_env, next)
|> emit_result(start_time, prefix, req_env)
rescue
e ->
stacktrace = System.stacktrace()
metadata = %{env: req_env, exception: e, stacktrace: stacktrace}
result =
try do
Tesla.run(env, next)
rescue
e ->
stacktrace = System.stacktrace()
metadata = %{env: env, exception: e, stacktrace: stacktrace}

:telemetry.execute(
prefix ++ [:tesla, :request, :exception],
%{duration: System.monotonic_time() - start_time},
metadata
)
:telemetry.execute(
prefix ++ [:tesla, :request, :exception],
%{duration: System.monotonic_time() - start_time},
metadata
)

reraise e, stacktrace
end
reraise e, stacktrace
end

emit_stop(result, start_time, prefix, env)

result
end

defp emit_start(req_env, start_time, prefix) do
defp emit_start(env, start_time, prefix) do
:telemetry.execute(prefix ++ [:tesla, :request, :start], %{time: start_time}, %{
env: req_env
env: env
})
end

defp emit_result(result, start_time, prefix, req_env) do
try do
result
after
case result do
{:ok, env} ->
:telemetry.execute(
prefix ++ [:tesla, :request, :stop],
%{duration: System.monotonic_time() - start_time},
%{env: env}
)
defp emit_stop(result, start_time, prefix, req_env) do
duration = System.monotonic_time() - start_time

{:error, error} ->
:telemetry.execute(
prefix ++ [:tesla, :request, :error],
%{duration: System.monotonic_time() - start_time},
%{env: req_env, reason: error}
)
end
case result do
{:ok, env} ->
:telemetry.execute(
prefix ++ [:tesla, :request, :stop],
%{duration: duration},
%{env: env}
)

{:error, error} ->
:telemetry.execute(
prefix ++ [:tesla, :request, :error],
%{duration: duration},
%{env: req_env, reason: error}
)
end

# retained for backwards compatibility - remove in 2.0
:telemetry.execute([:tesla, :request], %{request_time: duration}, %{result: result})
end
end
end
2 changes: 1 addition & 1 deletion mix.exs
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ defmodule Tesla.Mixfile do

# other
{:fuse, "~> 2.4", optional: true},
{:telemetry, "~> 0.3", optional: true},
{:telemetry, "~> 0.4", optional: true},

# testing & docs
{:excoveralls, "~> 0.8", only: :test},
Expand Down

0 comments on commit 4b961cc

Please sign in to comment.