Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Inspect Elixir exception module name in record_exception #804

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 3 additions & 11 deletions apps/opentelemetry_api/lib/open_telemetry/span.ex
Original file line number Diff line number Diff line change
Expand Up @@ -120,25 +120,17 @@ defmodule OpenTelemetry.Span do
@spec add_events(OpenTelemetry.span_ctx(), [OpenTelemetry.event()]) :: boolean()
defdelegate add_events(span_ctx, events), to: :otel_span

defguardp is_exception?(term)
when is_map(term) and :erlang.is_map_key(:__struct__, term) and
is_atom(:erlang.map_get(:__struct__, term)) and
:erlang.is_map_key(:__exception__, term) and
:erlang.map_get(:__exception__, term) == true

@doc """
Record an exception as an event, following the semantics convetions for exceptions.
Record an exception as an event, following the semantic conventions for exceptions.

If trace is not provided, the stacktrace is retrieved from `Process.info/2`
"""
@spec record_exception(OpenTelemetry.span_ctx(), Exception.t()) :: boolean()
def record_exception(span_ctx, exception, trace \\ nil, attributes \\ [])

def record_exception(span_ctx, exception, trace, attributes) when is_exception?(exception) do
exception_type = to_string(exception.__struct__)

def record_exception(span_ctx, %type{__exception__: true} = exception, trace, attributes) do
exception_attributes = [
{:"exception.type", exception_type},
{:"exception.type", inspect(type)},
{:"exception.message", Exception.message(exception)},
{:"exception.stacktrace", Exception.format_stacktrace(trace)}
]
Expand Down
4 changes: 4 additions & 0 deletions apps/opentelemetry_api/mix.exs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ defmodule OpenTelemetry.MixProject do
description: to_string(Keyword.fetch!(desc, :description)),
elixir: "~> 1.8",
start_permanent: Mix.env() == :prod,
elixirc_paths: elixirc_paths(Mix.env()),
deps: [
{:eqwalizer_support,
git: "https://github.com/whatsapp/eqwalizer.git",
Expand All @@ -35,6 +36,9 @@ defmodule OpenTelemetry.MixProject do

def application, do: []

defp elixirc_paths(:test), do: ["test/support", "lib"]
defp elixirc_paths(_), do: ["lib"]

defp package() do
[
description: "OpenTelemetry API",
Expand Down
76 changes: 76 additions & 0 deletions apps/opentelemetry_api/src/otel_span_mailbox.erl
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
%%%------------------------------------------------------------------------
%% Copyright 2024, OpenTelemetry Authors
%% Licensed under the Apache License, Version 2.0 (the "License");
%% you may not use this file except in compliance with the License.
%% You may obtain a copy of the License at
%%
%% http://www.apache.org/licenses/LICENSE-2.0
%%
%% Unless required by applicable law or agreed to in writing, software
%% distributed under the License is distributed on an "AS IS" BASIS,
%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
%% See the License for the specific language governing permissions and
%% limitations under the License.
%%
%% @doc
%% This module implements the `otel_span` API, but sends the data to the current
%% process's mailbox rather than storing it anywhere, so that it can be inspected
%% in tests.
%% @end
%%%-------------------------------------------------------------------------
-module(otel_span_mailbox).

-export([
end_span/1,
end_span/2,
set_attribute/3,
set_attributes/2,
add_event/3,
add_events/2,
set_status/2,
update_name/2]).

-include("opentelemetry.hrl").

-spec end_span(opentelemetry:span_ctx() | undefined) -> boolean().
end_span(SpanCtx) ->
self() ! {?FUNCTION_NAME, SpanCtx},
true.

Check warning on line 38 in apps/opentelemetry_api/src/otel_span_mailbox.erl

View check run for this annotation

Codecov / codecov/patch

apps/opentelemetry_api/src/otel_span_mailbox.erl#L37-L38

Added lines #L37 - L38 were not covered by tests

-spec end_span(opentelemetry:span_ctx() | undefined,
integer() | undefined) -> boolean().
end_span(SpanCtx, Timestamp) ->
self() ! {?FUNCTION_NAME, SpanCtx, Timestamp},
true.

Check warning on line 44 in apps/opentelemetry_api/src/otel_span_mailbox.erl

View check run for this annotation

Codecov / codecov/patch

apps/opentelemetry_api/src/otel_span_mailbox.erl#L43-L44

Added lines #L43 - L44 were not covered by tests

-spec set_attribute(opentelemetry:span_ctx() | undefined,
opentelemetry:attribute_key(),
opentelemetry:attribute_value()) -> boolean().
set_attribute(SpanCtx, Key, Value) ->
self() ! {?FUNCTION_NAME, SpanCtx, Key, Value},
true.

-spec set_attributes(opentelemetry:span_ctx() | undefined, opentelemetry:attributes_map()) -> boolean().
set_attributes(SpanCtx, NewAttributes) ->
self() ! {?FUNCTION_NAME, SpanCtx, NewAttributes},
true.

Check warning on line 56 in apps/opentelemetry_api/src/otel_span_mailbox.erl

View check run for this annotation

Codecov / codecov/patch

apps/opentelemetry_api/src/otel_span_mailbox.erl#L55-L56

Added lines #L55 - L56 were not covered by tests

-spec add_event(opentelemetry:span_ctx() | undefined, unicode:unicode_binary(), opentelemetry:attributes_map()) -> boolean().
add_event(SpanCtx, Name, Attributes) ->
self() ! {?FUNCTION_NAME, SpanCtx, Name, Attributes},
true.

-spec add_events(opentelemetry:span_ctx() | undefined, [opentelemetry:event()]) -> boolean().
add_events(SpanCtx, NewEvents) ->
self() ! {?FUNCTION_NAME, SpanCtx, NewEvents},
true.

-spec set_status(opentelemetry:span_ctx() | undefined, opentelemetry:status()) -> boolean().
set_status(SpanCtx, Status) ->
self() ! {?FUNCTION_NAME, SpanCtx, Status},
true.

-spec update_name(opentelemetry:span_ctx() | undefined, opentelemetry:span_name()) -> boolean().
update_name(SpanCtx, Name) ->
self() ! {?FUNCTION_NAME, SpanCtx, Name},
true.

Check warning on line 76 in apps/opentelemetry_api/src/otel_span_mailbox.erl

View check run for this annotation

Codecov / codecov/patch

apps/opentelemetry_api/src/otel_span_mailbox.erl#L75-L76

Added lines #L75 - L76 were not covered by tests
71 changes: 71 additions & 0 deletions apps/opentelemetry_api/src/otel_tracer_test.erl
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
%%%------------------------------------------------------------------------
%% Copyright 2024, OpenTelemetry Authors
%% Licensed under the Apache License, Version 2.0 (the "License");
%% you may not use this file except in compliance with the License.
%% You may obtain a copy of the License at
%%
%% http://www.apache.org/licenses/LICENSE-2.0
%%
%% Unless required by applicable law or agreed to in writing, software
%% distributed under the License is distributed on an "AS IS" BASIS,
%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
%% See the License for the specific language governing permissions and
%% limitations under the License.
%%
%% @doc
%% This module is used for testing the API by arranging for the calls that would
%% have been made to the SDK instead be send to the current process as
%% messages. This allows the test process to inspect and assert on them.
%% @end
%%%-------------------------------------------------------------------------
-module(otel_tracer_test).

-behaviour(otel_tracer).

-export([set_default/0,
start_span/4,
with_span/5,
end_span/2]).

-include("opentelemetry.hrl").
-include("otel_tracer.hrl").

%% @doc This helper acts as a default tracer provider that can be used in tests
%% to point to this tracer, either using Elixir or Erlang, since Elixir won't
%% have access to the necessary Erlang macro.
set_default() ->
opentelemetry:set_default_tracer(?GLOBAL_TRACER_PROVIDER_NAME, {?MODULE, []}),
ok.

-spec start_span(otel_ctx:t(), opentelemetry:tracer(), opentelemetry:span_name(),
otel_span:start_config()) -> opentelemetry:span_ctx().
start_span(Ctx, Tracer, Name, Opts) ->
self() ! {?FUNCTION_NAME, Ctx, Tracer, Name, Opts},
#span_ctx{trace_id=rand:uniform(2 bsl 127 - 1), %% 2 shifted left by 127 == 2 ^ 128
span_id=rand:uniform(2 bsl 63 - 1), %% 2 shifted left by 63 == 2 ^ 64
trace_flags=0,
tracestate=otel_tracestate:new(),
is_valid=true,
is_recording=true,
%% The critical functionality here is to set the span_sdk to the
%% one that sends messages to the process mailbox.
span_sdk={otel_span_mailbox, []}}.

-spec with_span(otel_ctx:t(), opentelemetry:tracer(), opentelemetry:span_name(),
otel_span:start_config(), otel_tracer:traced_fun(T)) -> T.
with_span(Ctx, Tracer, SpanName, Opts, Fun) ->
self() ! {?FUNCTION_NAME, Ctx, Tracer, SpanName, Opts, Fun},
SpanCtx = start_span(Ctx, Tracer, SpanName, Opts),
Ctx1 = otel_tracer:set_current_span(Ctx, SpanCtx),
otel_ctx:attach(Ctx1),
try
Fun(SpanCtx)
after
otel_ctx:attach(Ctx)
end.

-spec end_span(opentelemetry:tracer(), opentelemetry:span_ctx())
-> boolean() | {error, term()}.
end_span(Tracer, Ctx) ->
self() ! {?FUNCTION_NAME, Tracer, Ctx},
true.

Check warning on line 71 in apps/opentelemetry_api/src/otel_tracer_test.erl

View check run for this annotation

Codecov / codecov/patch

apps/opentelemetry_api/src/otel_tracer_test.erl#L70-L71

Added lines #L70 - L71 were not covered by tests
32 changes: 26 additions & 6 deletions apps/opentelemetry_api/test/open_telemetry_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,14 @@ defmodule OpenTelemetryTest do
require OpenTelemetry.Ctx, as: Ctx

require Record
@fields Record.extract(:span_ctx, from_lib: "opentelemetry_api/include/opentelemetry.hrl")
Record.defrecordp(:span_ctx, @fields)

@fields Record.extract(:status, from_lib: "opentelemetry_api/include/opentelemetry.hrl")
Record.defrecordp(:status, @fields)
@otel_include "opentelemetry_api/include/opentelemetry.hrl"
Record.defrecordp(:span_ctx, Record.extract(:span_ctx, from_lib: @otel_include))
Record.defrecordp(:status, Record.extract(:status, from_lib: @otel_include))

setup_all do
:otel_tracer_test.set_default()
end

test "current_span tracks last set_span" do
span_ctx1 = Tracer.start_span("span-1")
Expand Down Expand Up @@ -103,8 +106,8 @@ defmodule OpenTelemetryTest do
Tracer.with_span "span-1" do
span = Tracer.current_span_ctx()

assert Span.hex_trace_id(span) == "00000000000000000000000000000000"
assert Span.hex_span_id(span) == "0000000000000000"
assert Span.hex_trace_id(span) =~ ~r/[0-9a-f]{32}/
assert Span.hex_span_id(span) =~ ~r/[0-9a-f]{16}/
end
end

Expand Down Expand Up @@ -144,4 +147,21 @@ defmodule OpenTelemetryTest do
Ctx.detach(token)
assert %{"a" => {"b", []}} = Baggage.get_all()
end

test "Span.record_exception" do
Tracer.with_span "exceptional span" do
Tracer.record_exception(%RuntimeError{message: "too awesome"})
end

assert_received {:add_event, _span_ctx, :exception, attributes}

assert %{
"exception.type": "RuntimeError",
"exception.stacktrace": stacktrace,
"exception.message": "too awesome"
} = attributes

assert is_binary(stacktrace)
assert String.contains?(stacktrace, "\n")
end
end
2 changes: 1 addition & 1 deletion test/otel_tests.exs
Original file line number Diff line number Diff line change
Expand Up @@ -241,7 +241,7 @@ defmodule OtelTests do
attributes =
:otel_attributes.new(
[
{:"exception.type", "Elixir.RuntimeError"},
{:"exception.type", "RuntimeError"},
{:"exception.message", "my error message"},
{:"exception.stacktrace", stacktrace}
],
Expand Down
Loading