Instrument your Erlang application with OpenTelemetry
This walkthrough shows how to add observability to your Erlang application using the OpenTelemetry Erlang libraries and tools.
Feature | Supported |
---|---|
Automatic Instrumentation | No |
Automatic OneAgent Ingestion | No |
Prerequisites
- Dynatrace version 1.222+
- For tracing, W3C Trace Context is enabled
- From the Dynatrace menu, go to Settings > Preferences > OneAgent features.
- Turn on Send W3C Trace Context HTTP headers.
Get the Dynatrace access details
Determine the API base URL
For details on how to assemble the base OTLP endpoint URL, see Export with OTLP.
The URL should end in /api/v2/otlp
.
Get API access token
The access token for ingesting traces, logs, and metrics can be generated in your Dynatrace menu under Access tokens.
Export with OTLP has more details on the format and the necessary access scopes.
Set up OpenTelemetry
-
Add the current versions of the following dependencies to
rebar.config
.1{deps, [2 {opentelemetry_api, "~> 1.2.1"},3 {opentelemetry, "~> 1.3.0"},4 {opentelemetry_exporter, "~> 1.4.1"}5]}. -
Add the following dependencies to your
.app.src
file in thesrc
directory.1{applications, [kernel,2 stdlib,3 opentelemetry_api,4 opentelemetry,5 opentelemetry_exporter]} -
Add the following configuration to
config/sys.config
and replace[URL]
and[TOKEN]
with the respective values for the Dynatrace URL and access token.1[2 {text_map_propagators, [baggage, trace_context]},34 {otel_getting_started, []},56 {opentelemetry,7 [{span_processor, batch},8 {traces_exporter, otlp},9 {resource,10 [{service,11 #{name => "erlang-quickstart", version => "1.0.1"} %%TODO Replace with the name and version of your application12 }]13 },14 {resource_detectors, [15 otel_resource_env_var,16 otel_resource_app_env,17 extra_metadata18 ]}19 ]20 },21 {opentelemetry_exporter,22 [{otlp_protocol, http_protobuf},23 {otlp_traces_endpoint, "[URL]"}, %%TODO Replace [URL] to your SaaS/Managed URL as mentioned in the next step24 {otlp_headers, [{"Authorization", "Api-Token [TOKEN]"}]} %%TODO Replace [TOKEN] with your API Token as mentioned in the next step25 ]}26]. -
Save the following code to
src/extra_metadata.erl
.1-module(extra_metadata).2-behaviour(otel_resource_detector).3-export([get_resource/1]).45get_resource(_) ->6 Metadata = otel_resource:create(otel_resource_app_env:parse(get_metadata("/var/lib/dynatrace/enrichment/dt_metadata.properties")), []),7 {ok, MetadataFilePath} = file:read_file("dt_metadata_e617c525669e072eebe3d0f08212e8f2.properties"),8 Metadata2 = otel_resource:create(otel_resource_app_env:parse(get_metadata(MetadataFilePath)), []),9 Metadata3 = otel_resource:create(otel_resource_app_env:parse(get_metadata("/var/lib/dynatrace/enrichment/dt_host_metadata.properties")), []),10 otel_resource:merge(otel_resource:merge(Metadata, Metadata2), Metadata3).11 otel_resource:merge(Metadata, Metadata2).1213get_metadata(FileName) ->14try15 {ok, MetadataFile} = file:read_file(FileName),16 Lines = binary:split(MetadataFile, <<"\n">>, [trim, global]),17 make_tuples(Lines, [])18catch _:_ -> "Metadata not found, safe to continue"19end.2021make_tuples([Line|Lines], Acc) ->22 [Key, Value] = binary:split(Line, <<"=">>),23 make_tuples(Lines, [{Key, Value}|Acc]);24make_tuples([], Acc) -> Acc.
Instrument your application
Add tracing
Spans are started with the macro with_span
and accept an optional list of span attributes, as well as the code block for this span. The span will automatically finish when the code block returns.
1-export([init/2]).23-include_lib("opentelemetry_api/include/otel_tracer.hrl").4-include_lib("opentelemetry/include/otel_resource.hrl").56init( Req, State ) ->7 ?with_span(<<"parent_span">>, #{attributes => [ %%TODO Add span name8 {<<"my-key-1">>, <<"my-value-1">>}] %%TODO Add attributes at span creation9 }, fun child_function/1),10 %% Your code goes here111213child_function(_SpanCtx) ->14 ?with_span(<<"child_span">>, #{},15 fun(_ChildSpanCtx) ->16 ?set_attributes([{<<"child-key-1">>, <<"child-value-1">>}]) %%TODO Add attributes after span creation17 end).
Collect metrics
OpenTelemetry metrics for Erlang are under development.
Connect logs
OpenTelemetry logging for Erlang is under development.
Ensure context propagation optional
Context propagation is particularly important when network calls (for example, REST) are involved.
Extracting the context when receiving a request
For extracting information on an existing context, we pass the headers to the otel_propagator_text_map.extract
function, which parses the context information provided by the headers and sets the current context based on that.
1%% Get Headers from incoming request2Headers = maps:get(headers, Req),3otel_propagator_text_map:extract(maps:to_list(Headers)),45SpanCtx = ?start_span(<<"span-name">>),67%% As we used `otel_propagator_text_map` the current context is from the parent span8Ctx = otel_ctx:get_current(),910proc_lib:spawn_link(fun() ->11 %% Start span and set as current12 otel_ctx:attach(Ctx),13 ?set_current_span(SpanCtx),1415 %% Create response16 Resp = cowboy_req:reply(17 200,18 #{<<"content-type">> => <<"application/json">>},19 <<"{\"message\": \"hello world\"}">>,20 Req21 ),2223 {ok, Resp, State},24 ?end_span(SpanCtx)
Injecting the context when sending requests
The following example uses otel_propagator_text_map:inject
to provide the HTTP headers (necessary for context propagation) in NewHeaders
, which we eventually merge with the existing header object Headers
and pass to the httpc:request
call, which allows the receiving endpoint to continue the trace with the provided information.
1?with_span(<<"span-name">>, #{},2 fun(_ChildSpanCtx) ->34 %% a custom header example5 Headers = [{"content-type", "application/json"}, {"X-Custom-Header", "some-value"}],67 %% we convert the traceparent information and merge the 2 headers as8 %% httpc:request requires tuples of strings9 Tmp = [],10 NewHeaders = headers_list(otel_propagator_text_map:inject(opentelemetry:get_text_map_injector(), Tmp)),11 MergedHeaders = lists:append(Headers, NewHeaders),1213 {ok, Res} = httpc:request(get, {URL, MergedHeaders}, [], []),14 io:format("Response: ~p~n", [Res])15 end).1617headers_list(Headers) ->18 [{binary_to_list(Name), binary_to_list(Value)} || {Name, Value} <- Headers].
Configure data capture to meet privacy requirements optional
While Dynatrace automatically captures all OpenTelemetry attributes, only attribute values specified in the allowlist are stored and displayed in the Dynatrace web UI. This prevents accidental storage of personal data, so you can meet your privacy requirements and control the amount of monitoring data stored.
To view your custom attributes, you need to allow them in the Dynatrace web UI first. To learn how to configure attribute storage and masking, see Attribute redaction.
Verify data ingestion into Dynatrace
Once you have finished the instrumentation of your application, perform a couple of test actions to create and send demo traces, metrics, and logs and verify that they were correctly ingested into Dynatrace.
To do that for traces, in the Dynatrace menu, go to Distributed traces and select the Ingested traces tab. If you use OneAgent, select PurePaths instead.
Metrics and logs can be found under their respective entries at Observe and explore.