zf

zenflows testing
git clone https://s.sonu.ch/~srfsh/zf.git
Log | Files | Refs | Submodules | README | LICENSE

logger.ex (1420B)


      1 defmodule Plug.Logger do
      2   @moduledoc """
      3   A plug for logging basic request information in the format:
      4 
      5       GET /index.html
      6       Sent 200 in 572ms
      7 
      8   To use it, just plug it into the desired module.
      9 
     10       plug Plug.Logger, log: :debug
     11 
     12   ## Options
     13 
     14     * `:log` - The log level at which this plug should log its request info.
     15       Default is `:info`.
     16       The [list of supported levels](https://hexdocs.pm/logger/Logger.html#module-levels)
     17       is available in the `Logger` documentation.
     18 
     19   """
     20 
     21   require Logger
     22   alias Plug.Conn
     23   @behaviour Plug
     24 
     25   @impl true
     26   def init(opts) do
     27     Keyword.get(opts, :log, :info)
     28   end
     29 
     30   @impl true
     31   def call(conn, level) do
     32     Logger.log(level, fn ->
     33       [conn.method, ?\s, conn.request_path]
     34     end)
     35 
     36     start = System.monotonic_time()
     37 
     38     Conn.register_before_send(conn, fn conn ->
     39       Logger.log(level, fn ->
     40         stop = System.monotonic_time()
     41         diff = System.convert_time_unit(stop - start, :native, :microsecond)
     42         status = Integer.to_string(conn.status)
     43 
     44         [connection_type(conn), ?\s, status, " in ", formatted_diff(diff)]
     45       end)
     46 
     47       conn
     48     end)
     49   end
     50 
     51   defp formatted_diff(diff) when diff > 1000, do: [diff |> div(1000) |> Integer.to_string(), "ms"]
     52   defp formatted_diff(diff), do: [Integer.to_string(diff), "µs"]
     53 
     54   defp connection_type(%{state: :set_chunked}), do: "Chunked"
     55   defp connection_type(_), do: "Sent"
     56 end