@@ -46,10 +46,11 @@ defmodule ErrorTracker.Integrations.Plug do
4646 defoverridable call: 2
4747
4848 def call ( conn , opts ) do
49+ unquote ( __MODULE__ ) . set_context ( conn )
4950 super ( conn , opts )
5051 rescue
5152 e in Plug.Conn.WrapperError ->
52- unquote ( __MODULE__ ) . report_error ( conn , e , e . stack )
53+ unquote ( __MODULE__ ) . report_error ( e . conn , e . reason , e . stack )
5354
5455 Plug.Conn.WrapperError . reraise ( e )
5556
@@ -68,13 +69,46 @@ defmodule ErrorTracker.Integrations.Plug do
6869 end
6970 end
7071
71- def report_error ( _conn , reason , stack ) do
72+ def report_error ( conn , reason , stack ) do
7273 unless Process . get ( :error_tracker_router_exception_reported ) do
7374 try do
74- ErrorTracker . report ( reason , stack )
75+ ErrorTracker . report ( reason , stack , build_context ( conn ) )
7576 after
7677 Process . put ( :error_tracker_router_exception_reported , true )
7778 end
7879 end
7980 end
81+
82+ def set_context ( conn = % Plug.Conn { } ) do
83+ conn |> build_context |> ErrorTracker . set_context ( )
84+ end
85+
86+ defp build_context ( conn = % Plug.Conn { } ) do
87+ % {
88+ "request.host" => conn . host ,
89+ "request.path" => conn . request_path ,
90+ "request.query" => conn . query_string ,
91+ "request.method" => conn . method ,
92+ "request.ip" => remote_ip ( conn ) ,
93+ "request.headers" => Map . new ( conn . req_headers ) ,
94+ # Depending on the error source, the request params may have not been fetched yet
95+ "request.params" => unless ( is_struct ( conn . params , Plug.Conn.Unfetched ) , do: conn . params )
96+ }
97+ end
98+
99+ defp remote_ip ( conn = % Plug.Conn { } ) do
100+ remote_ip =
101+ case Plug.Conn . get_req_header ( conn , "x-forwarded-for" ) do
102+ [ x_forwarded_for | _ ] ->
103+ x_forwarded_for |> String . split ( "," , parts: 2 ) |> List . first ( )
104+
105+ [ ] ->
106+ case :inet . ntoa ( conn . remote_ip ) do
107+ { :error , _ } -> ""
108+ address -> to_string ( address )
109+ end
110+ end
111+
112+ String . trim ( remote_ip )
113+ end
80114end
0 commit comments