Skip to content

Commit

Permalink
Add logger filter
Browse files Browse the repository at this point in the history
  • Loading branch information
reachfh committed Dec 23, 2023
1 parent 8c2df17 commit a4ab074
Show file tree
Hide file tree
Showing 2 changed files with 61 additions and 0 deletions.
33 changes: 33 additions & 0 deletions src/opentelemetry_xray_logger_filter.erl
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
%% @doc
%%
%% Erlang logger filter to format trace id in X-Ray format.
%%
%% This module implements a logger filter which formats the trace_id in X-Ray
%% format so log messages can be correlated with traces.
%%
%% See:
%% * https://www.erlang.org/doc/man/logger#type-filter
%% * https://github.com/aws/aws-xray-sdk-python/issues/188
%% @end
-module(opentelemetry_xray_logger_filter).

-include_lib("kernel/include/logger.hrl").

-export([trace_id/2]).

-spec trace_id(LogEvent, Extra) -> logger:filter_return()
when LogEvent :: logger:log_event(),
Extra :: term().
trace_id(#{meta := #{trace_id := TraceId, span_id := SpanId} = Meta} = LogEvent, _Extra) when is_integer(TraceId), is_integer(SpanId) ->
EncodedTraceId = opentelemetry_xray_propagator:encode_trace_id(TraceId),
EncodedSpanId = opentelemetry_xray_propagator:encode_span_id(SpanId),
NewId = otel_utils:assert_to_binary(["1-", EncodedTraceId, "@", EncodedSpanId]),
NewMeta0 = maps:update(trace_id, NewId, Meta),
NewMeta1 = maps:remove(span_id, NewMeta0),
maps:update(meta, NewMeta1, LogEvent);
trace_id(#{meta := #{trace_id := TraceId} = Meta} = LogEvent, _Extra) when is_integer(TraceId) ->
EncodedTraceId = opentelemetry_xray_propagator:encode_trace_id(TraceId),
NewId = otel_utils:assert_to_binary(["1-", EncodedTraceId]),
NewMeta = maps:update(trace_id, NewId, Meta),
maps:update(meta, NewMeta, LogEvent);
trace_id(LogEvent, _Extra) -> LogEvent.
28 changes: 28 additions & 0 deletions test/opentelemetry_xray_logger_filter_SUITE.erl
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
-module(opentelemetry_xray_logger_filter_SUITE).

-compile(export_all).

-include_lib("common_test/include/ct.hrl").
-include_lib("kernel/include/logger.hrl").
-include_lib("stdlib/include/assert.hrl").

all() -> [encode].

encode() -> [{docs, "encode"}].

encode(_) ->
TraceId = binary_to_integer(<<"5759e988bd862e3fe1be46a994272793">>, 16),
SpanId = binary_to_integer(<<"53995c3f42cd8ad8">>, 16),
?assertMatch(
#{meta := #{trace_id := <<"1-5759e988-bd862e3fe1be46a994272793">>}},
opentelemetry_xray_logger_filter:trace_id(#{meta => #{trace_id => TraceId}}, undefined)
),
?assertMatch(
#{meta := #{trace_id := <<"1-5759e988-bd862e3fe1be46a994272793@53995c3f42cd8ad8">>}},
opentelemetry_xray_logger_filter:trace_id(#{meta => #{trace_id => TraceId, span_id => SpanId}}, undefined)
),
?assertMatch(
#{meta := #{}},
opentelemetry_xray_logger_filter:trace_id(#{meta => #{}}, undefined)
),
ok.

0 comments on commit a4ab074

Please sign in to comment.