# `Snakepit.Telemetry.Span`
[🔗](https://github.com/nshkrdotcom/snakepit/blob/v0.13.0/lib/snakepit/telemetry/span.ex#L1)

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)

# `event`

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

# `metadata`

```elixir
@type metadata() :: map()
```

# `span_ref`

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

# `end_span`

```elixir
@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`

```elixir
@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`

```elixir
@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`

```elixir
@spec span(event(), metadata(), (-&gt; 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`

```elixir
@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)

---

*Consult [api-reference.md](api-reference.md) for complete listing*
