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 ab37761
Show file tree
Hide file tree
Showing 2 changed files with 43 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
- `:extra_attrs` - extra span attributes
"""

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))
extra_attrs = Keyword.get(opts, :extra_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(extra_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, extra_attrs) do
extra_attrs
|> Map.merge(build_attrs(env))
|> OpenTelemetry.Tracer.set_attributes()

result
end

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

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,41 @@ defmodule Tesla.Middleware.OpenTelemetryTest do
assert_receive {:span, span(name: "POST :my-high-cardinality-url", attributes: _attributes)}
end

test "with extra attrs",
%{
bypass: bypass
} do
defmodule TestClient do
def get(client) do
params = [id: ~c"3"]

Tesla.get(client, "/users/:id", opts: [path_params: params])
end

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

Tesla.client(middleware)
end
end

Bypass.expect_once(bypass, "GET", "/users/3", 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 attributes["peer.service"] == "myservicename"
end

test "uses custom span name function when passed in middleware opts",
%{
bypass: bypass
Expand Down

0 comments on commit ab37761

Please sign in to comment.