Packages
commanded
0.14.0-rc.0
1.4.10
1.4.9
1.4.8
1.4.7
1.4.6
1.4.3
1.4.2
1.4.1
1.4.0
1.4.0-rc.0
1.3.1
1.3.0
1.2.0
1.1.1
1.1.0
1.0.1
1.0.0
1.0.0-rc.1
1.0.0-rc.0
0.19.1
0.19.0
0.18.1
0.18.0
0.17.5
0.17.4
0.17.3
0.17.2
0.17.1
0.17.0
0.16.0
0.16.0-rc.1
0.16.0-rc.0
0.15.1
0.15.0
0.14.0
0.14.0-rc.0
0.13.0
0.12.0
0.11.0
0.10.0
0.9.0
0.8.5
0.8.4
0.8.3
0.8.1
0.8.0
0.7.1
0.6.2
0.6.1
0.6.0
0.4.0
0.3.1
0.3.0
0.2.1
0.2.0
0.1.0
Use Commanded to build your own Elixir applications following the CQRS/ES pattern.
Current section
Files
Jump to
Current section
Files
lib/commanded/middleware/logger.ex
defmodule Commanded.Middleware.Logger do
@moduledoc """
A `Commanded.Middleware` that logs each stage of the command dispatch using the Elixir `Logger`:
- Before dispatch.
- After successful dispatch.
- After failed dispatch.
"""
@behaviour Commanded.Middleware
alias Commanded.Middleware.Pipeline
import Pipeline
require Logger
def before_dispatch(%Pipeline{} = pipeline) do
Logger.info(fn -> "#{log_context(pipeline)} dispatch start" end)
assign(pipeline, :started_at, DateTime.utc_now)
end
def after_dispatch(%Pipeline{} = pipeline) do
Logger.info(fn -> "#{log_context(pipeline)} succeeded in #{formatted_diff(delta(pipeline))}" end)
pipeline
end
def after_failure(%Pipeline{assigns: %{error: error, error_reason: error_reason}} = pipeline) do
Logger.info(fn -> "#{log_context(pipeline)} failed #{inspect error} in #{formatted_diff(delta(pipeline))}" end)
Logger.info(fn -> inspect(error_reason) end)
pipeline
end
def after_failure(%Pipeline{assigns: %{error: error}} = pipeline) do
Logger.info(fn -> "#{log_context(pipeline)} failed #{inspect error} in #{formatted_diff(delta(pipeline))}" end)
pipeline
end
defp delta(%Pipeline{assigns: %{started_at: started_at}}) do
now_usecs = DateTime.utc_now |> DateTime.to_unix(:microseconds)
started_usecs = started_at |> DateTime.to_unix(:microseconds)
now_usecs - started_usecs
end
defp log_context(%Pipeline{command: command}) do
"#{inspect command.__struct__}"
end
defp formatted_diff(diff) when diff > 1_000_000, do: [diff |> div(1_000_000) |> Integer.to_string, "s"]
defp formatted_diff(diff) when diff > 1_000, do: [diff |> div(1_000) |> Integer.to_string, "ms"]
defp formatted_diff(diff), do: [diff |> Integer.to_string, "µs"]
end