Skip to content

Commit

Permalink
feat: add extra_attrs to tesla middleware
Browse files Browse the repository at this point in the history
  • Loading branch information
yordis committed Dec 26, 2024
1 parent a4ee9fe commit badf208
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ defmodule Tesla.Middleware.OpenTelemetry do
Defaults to calling `:otel_propagator_text_map.get_text_map_injector/0`
- `:mark_status_ok` - configures spans with a list of expected HTTP error codes to be marked as `ok`,
not as an error-containing spans
- `:trace_attrs` - trace attributes to be added to the span.
"""

alias OpenTelemetry.SemanticConventions.Trace
Expand All @@ -28,13 +29,14 @@ defmodule Tesla.Middleware.OpenTelemetry do

def call(env, next, opts) do
span_name = get_span_name(env, Keyword.get(opts, :span_name))
trace_attrs = Keyword.get(opts, :trace_attrs, %{})

OpenTelemetry.Tracer.with_span span_name, %{kind: :client} do
env
|> maybe_put_additional_ok_statuses(opts[:mark_status_ok])
|> maybe_propagate(Keyword.get(opts, :propagator, :opentelemetry.get_text_map_injector()))
|> Tesla.run(next)
|> set_span_attributes()
|> set_span_attributes(trace_attrs)
|> handle_result()
end
end
Expand Down Expand Up @@ -73,13 +75,15 @@ defmodule Tesla.Middleware.OpenTelemetry do

defp maybe_put_additional_ok_statuses(env, _additional_ok_statuses), do: env

defp set_span_attributes({_, %Tesla.Env{} = env} = result) do
OpenTelemetry.Tracer.set_attributes(build_attrs(env))
defp set_span_attributes({_, %Tesla.Env{} = env} = result, trace_attrs) do
trace_attrs
|> Map.merge(build_attrs(env))
|> OpenTelemetry.Tracer.set_attributes()

result
end

defp set_span_attributes(result) do
defp set_span_attributes(result, _trace_attrs) do
result
end

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,35 @@ defmodule Tesla.Middleware.OpenTelemetryTest do
end
end

test "span with trace attrs", %{bypass: bypass} do
defmodule TestClient do
def get(client) do
Tesla.get(client, "/users/")
end

def client(url) do
middleware = [
{Tesla.Middleware.BaseUrl, url},
{Tesla.Middleware.OpenTelemetry, trace_attrs: %{"peer.service" => "myservicename"}}
]

Tesla.client(middleware)
end
end

Bypass.expect_once(bypass, "GET", "/users", fn conn ->
Plug.Conn.resp(conn, 204, "")
end)

bypass.port
|> endpoint_url()
|> TestClient.client()
|> TestClient.get()

assert_receive {:span, span(name: "HTTP GET", attributes: attributes)}
assert %{"peer.service" => "myservicename"} = :otel_attributes.map(attributes)
end

test "Records spans for Tesla HTTP client", %{bypass: bypass} do
defmodule TestClient do
def get(client) do
Expand Down

0 comments on commit badf208

Please sign in to comment.