-
Notifications
You must be signed in to change notification settings - Fork 16
/
log_incoming.ex
43 lines (33 loc) · 1.13 KB
/
log_incoming.ex
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
defmodule Conduit.Plug.LogIncoming do
use Conduit.Plug.Builder
require Logger
@moduledoc """
Logs an incoming message and how long it takes to process it.
This is intended to be used in an incoming pipeline or subscriber.
## Examples
plug Conduit.Plug.LogIncoming
plug Conduit.Plug.LogIncoming, log: :debug
"""
def call(message, next, opts) do
level = Keyword.get(opts, :log, :info)
start = System.monotonic_time()
try do
Logger.log(level, fn ->
["Processing message from ", message.source]
end)
next.(message)
rescue
error ->
Logger.log(:error, Exception.format(:error, error))
reraise error, System.stacktrace()
after
Logger.log(level, fn ->
stop = System.monotonic_time()
diff = System.convert_time_unit(stop - start, :native, :microsecond)
["Processed message from ", message.source, " in ", formatted_diff(diff)]
end)
end
end
defp formatted_diff(diff) when diff > 1000, do: [diff |> div(1000) |> Integer.to_string(), "ms"]
defp formatted_diff(diff), do: [diff |> Integer.to_string(), "µs"]
end