Snakepit.Telemetry.Span (Snakepit v0.8.7)

View Source

Telemetry span helpers for wrapping operations.

Provides convenient helpers for emitting start/stop/exception telemetry events around function calls.

Usage

# Automatic span with function
result = Snakepit.Telemetry.Span.span(
  [:snakepit, :my_operation],
  %{pool: :default},
  fn -> do_operation() end
)

# Manual span management
span_ref = Snakepit.Telemetry.Span.start_span([:snakepit, :operation], %{})
# ... do work ...
Snakepit.Telemetry.Span.end_span(span_ref)

Summary

Functions

Ends a telemetry span.

Ends a telemetry span with additional metadata.

Executes a function wrapped in telemetry span events.

Starts a telemetry span.

Types

event()

@type event() :: [atom()]

metadata()

@type metadata() :: map()

span_ref()

@type span_ref() :: %{event: event(), start_time: integer(), metadata: metadata()}

Functions

end_span(span_ref)

@spec end_span(span_ref()) :: :ok

Ends a telemetry span.

Emits event ++ [:stop] with the duration measurement.

Examples

span_ref = Span.start_span([:myapp, :operation], %{})
# ... do work ...
Span.end_span(span_ref)

end_span(span_ref, additional_metadata)

@spec end_span(span_ref(), metadata()) :: :ok

Ends a telemetry span with additional metadata.

Merges the additional metadata with the original span metadata before emitting the stop event.

Examples

span_ref = Span.start_span([:myapp, :operation], %{})
result = do_work()
Span.end_span(span_ref, %{result: result, items_processed: 100})

end_span_exception(span_ref, kind, reason, stacktrace)

@spec end_span_exception(
  span_ref(),
  :error | :exit | :throw,
  term(),
  Exception.stacktrace()
) :: :ok

Ends a span with an exception.

Use this when you catch an exception but want to emit the exception telemetry event before re-raising or handling it.

Examples

span_ref = Span.start_span([:myapp, :operation], %{})
try do
  do_risky_work()
rescue
  e ->
    Span.end_span_exception(span_ref, :error, e, __STACKTRACE__)
    handle_error(e)
end

span(event, metadata, fun)

@spec span(event(), metadata(), (-> result)) :: result when result: any()

Executes a function wrapped in telemetry span events.

Emits event ++ [:start] before the function runs, and event ++ [:stop] after it completes successfully. If the function raises, throws, or exits, emits event ++ [:exception].

Examples

Span.span([:myapp, :operation], %{user_id: 123}, fn ->
  perform_operation()
end)

start_span(event, metadata \\ %{})

@spec start_span(event(), metadata()) :: span_ref()

Starts a telemetry span.

Returns a span reference that should be passed to end_span/1 or end_span/2.

Emits event ++ [:start] immediately.

Examples

span_ref = Span.start_span([:myapp, :operation], %{user_id: 123})
# ... do work ...
Span.end_span(span_ref)