Skip to content

Instantly share code, notes, and snippets.

@chvanikoff
Last active October 27, 2017 00:19

Revisions

  1. chvanikoff renamed this gist Jan 24, 2015. 1 changed file with 0 additions and 0 deletions.
  2. chvanikoff created this gist Jan 24, 2015.
    66 changes: 66 additions & 0 deletions Log http requests to Postgres
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,66 @@
    # defmodule Repo.Migrations.LogsHTTP do
    # use Ecto.Migration

    # def up do
    # execute """
    # CREATE TABLE logs_http(
    # id serial primary key,
    # request_id varchar(200),
    # method varchar(8),
    # path varchar(128),
    # params varchar(255),
    # inserted_at timestamp
    # )
    # """
    # end

    # def down do
    # execute "DROP TABLE logs_http"
    # end
    # end

    # To use place this code to app endpoint before(!) Plug.Logger
    # plug Plug.Log.HTTP

    defmodule Plug.Log.HTTP.Model do
    use Ecto.Model

    schema "logs_http" do
    field :request_id, :string
    field :method, :string
    field :path, :string
    field :params, :string
    timestamps updated_at: false
    end

    def write(log) do
    {:ok, Repo.insert(log)}
    end
    end

    defmodule Plug.Log.HTTP do
    alias Plug.Conn
    @behaviour Plug

    alias Plug.Log.HTTP.Model

    def init(opts), do: opts

    def call(conn, _config) do
    Conn.register_before_send(conn, fn conn ->
    log_conn_data(conn)
    conn
    end)
    end

    def log_conn_data(conn) do
    [request_id | _] = Conn.get_resp_header(conn, "x-request-id")
    log = %Model{
    request_id: request_id,
    method: conn.method,
    path: Conn.full_path(conn),
    params: Poison.encode!(conn.params)
    }
    Model.write(log)
    end
    end