Last active
October 27, 2017 00:19
-
-
Save chvanikoff/9b1799e6594c27e2823e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment