This repository has been archived by the owner on Mar 9, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 10
/
opentelemetry_phoenix.ex
247 lines (197 loc) · 6.83 KB
/
opentelemetry_phoenix.ex
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
defmodule OpentelemetryPhoenix do
@moduledoc """
OpentelemetryPhoenix uses Telemetry handlers to create OpenTelemetry spans.
## Usage
In your application start:
`OpentelemetryPhoenix.setup()`
"""
require OpenTelemetry.Tracer
require OpenTelemetry.Span
@type opts :: [endpoint_prefix()]
@typedoc "The endpoint prefix in your endpoint. Defaults to `[:phoenix, :endpoint]`"
@type endpoint_prefix :: {:endpoint_prefix, [atom()]}
@doc """
Initializes and configures the telemetry handlers.
"""
@spec setup(opts()) :: :ok
def setup(opts \\ []) do
opts = ensure_opts(opts)
_ = OpenTelemetry.register_application_tracer(:opentelemetry_phoenix)
attach_endpoint_start_handler(opts)
attach_endpoint_stop_handler(opts)
attach_exception_handler()
attach_router_start_handler()
attach_router_dispatch_exception_handler()
:ok
end
defp ensure_opts(opts), do: Keyword.merge(default_opts(), opts)
defp default_opts do
[endpoint_prefix: [:phoenix, :endpoint]]
end
@doc false
def attach_endpoint_start_handler(opts) do
:telemetry.attach(
{__MODULE__, :endpoint_start},
opts[:endpoint_prefix] ++ [:start],
&__MODULE__.handle_endpoint_start/4,
%{}
)
end
@doc false
def attach_endpoint_stop_handler(opts) do
:telemetry.attach(
{__MODULE__, :endpoint_stop},
opts[:endpoint_prefix] ++ [:stop],
&__MODULE__.handle_endpoint_stop/4,
%{}
)
end
@doc false
def attach_router_start_handler do
:telemetry.attach(
{__MODULE__, :router_dispatch_start},
[:phoenix, :router_dispatch, :start],
&__MODULE__.handle_router_dispatch_start/4,
%{}
)
end
@doc false
def attach_router_dispatch_exception_handler do
:telemetry.attach(
{__MODULE__, :router_dispatch_exception},
[:phoenix, :router_dispatch, :exception],
&__MODULE__.handle_router_dispatch_exception/4,
%{}
)
end
@doc false
def attach_exception_handler do
:telemetry.attach(
{__MODULE__, :endpoint_exception},
[:phoenix, :error_rendered],
&__MODULE__.handle_exception/4,
%{}
)
end
@doc false
def handle_endpoint_start(_event, _measurements, %{conn: conn}, _config) do
# TODO: maybe add config for what paths are traced
:ot_propagation.http_extract(conn.req_headers)
span_name = "HTTP #{conn.method}"
OpenTelemetry.Tracer.start_span(span_name, %{kind: :SERVER})
peer_data = Plug.Conn.get_peer_data(conn)
user_agent = header_value(conn, "user-agent")
peer_ip = Map.get(peer_data, :address)
attributes = [
{"http.client_ip", client_ip(conn)},
{"http.host", conn.host},
{"http.method", conn.method},
{"http.scheme", "#{conn.scheme}"},
{"http.target", conn.request_path},
{"http.user_agent", user_agent},
{"net.host.ip", to_string(:inet_parse.ntoa(conn.remote_ip))},
{"net.host.port", conn.port},
{"net.peer.ip", to_string(:inet_parse.ntoa(peer_ip))},
{"net.peer.port", peer_data.port},
{"net.transport", "IP.TCP"}
]
OpenTelemetry.Span.set_attributes(attributes)
end
def handle_endpoint_stop(_event, _measurements, %{conn: conn}, _config) do
if in_span?() do
OpenTelemetry.Span.set_attribute("http.status", conn.status)
span_status(conn.status) |> OpenTelemetry.Span.set_status()
OpenTelemetry.Tracer.end_span()
end
end
def handle_router_dispatch_start(_event, _measurements, meta, _config) do
if in_span?() do
OpenTelemetry.Span.update_name(meta.route)
attributes = [
{"phoenix.plug", to_string(meta.plug)},
{"phoenix.action", to_string(meta.plug_opts)}
]
OpenTelemetry.Span.set_attributes(attributes)
end
end
def handle_exception(_event, _measurements, meta, _config) do
if in_span?() do
exception_attrs = [
{"type", to_string(meta.kind)},
{"message", meta.reason.message},
{"stacktrace", "#{inspect(meta.stacktrace)}"}
]
# TODO: events don't seem to be supported in Jaeger or Zipkin.
OpenTelemetry.Span.add_event("exception", exception_attrs)
OpenTelemetry.Span.set_attributes([{"http.status", meta.status}])
span_status(meta.status) |> OpenTelemetry.Span.set_status()
OpenTelemetry.Tracer.end_span()
end
end
def handle_router_dispatch_exception(_event, _measurements, meta, _config) do
if in_span?() do
exception_attrs = [
{"type", to_string(meta.kind)},
{"message", meta.reason.message},
{"stacktrace", "#{inspect(meta.stacktrace)}"}
]
# TODO: events don't seem to be supported in Jaeger or Zipkin.
OpenTelemetry.Span.add_event("exception", exception_attrs)
OpenTelemetry.Span.set_attributes([{"http.status", 500}])
span_status(500) |> OpenTelemetry.Span.set_status()
OpenTelemetry.Tracer.end_span()
end
end
# 300s as Ok for now until redirect condition handled
# https://github.com/open-telemetry/opentelemetry-specification/blob/master/specification/trace/semantic_conventions/http.md#status
# move this to opentelemetry_erlang_api
defp span_status(code, msg \\ nil) do
case code do
code when code >= 100 and code < 300 ->
OpenTelemetry.status(:Ok, msg || "Ok")
code when code >= 300 and code < 400 ->
OpenTelemetry.status(:Ok, msg || "Ok")
401 ->
OpenTelemetry.status(:Unauthenticated, msg || "Unauthorized")
403 ->
OpenTelemetry.status(:PermissionDenied, msg || "Forbidden")
404 ->
OpenTelemetry.status(:NotFound, msg || "Not Found")
412 ->
OpenTelemetry.status(:FailedPrecondition, msg || "Failed Precondition")
416 ->
OpenTelemetry.status(:OutOfRange, msg || "Range Not Satisfiable")
429 ->
OpenTelemetry.status(:ResourceExhausted, msg || "Too Many Requests")
code when code >= 400 and code < 500 ->
OpenTelemetry.status(:InvalidArgument, msg || "Bad Argument")
501 ->
OpenTelemetry.status(:Unimplemented, msg || "Not Implemented")
503 ->
OpenTelemetry.status(:Unavailable, msg || "Service Unavailable")
504 ->
OpenTelemetry.status(:DeadlineExceeded, msg || "Gateway Timeout")
code when code >= 500 ->
OpenTelemetry.status(:InternalError, msg || "Internal Error")
_ ->
OpenTelemetry.status(:UnknownError, msg || "Unknown Status")
end
end
defp client_ip(%{remote_ip: remote_ip} = conn) do
case Plug.Conn.get_req_header(conn, "x-forwarded-for") do
[] ->
to_string(:inet_parse.ntoa(remote_ip))
[client | _] ->
client
end
end
defp header_value(conn, header) do
case Plug.Conn.get_req_header(conn, header) do
[] ->
""
[value | _] ->
value
end
end
defp in_span?, do: OpenTelemetry.Tracer.current_ctx() != :undefined
end