### telemetry:span/3 Source: https://telemetry.hexdocs.pm/readme.md Generates start and stop or exception events for a given function. Emits EventPrefix ++ [start] on invocation, EventPrefix ++ [stop] on success, and EventPrefix ++ [exception] on error. Measurements include system_time for start events and duration for stop/exception events, plus monotonic_time for all. ```APIDOC ## telemetry:span/3 ### Description Generates start and stop or exception events for a given function. Emits EventPrefix ++ [start] on invocation, EventPrefix ++ [stop] on success, and EventPrefix ++ [exception] on error. Measurements include system_time for start events and duration for stop/exception events, plus monotonic_time for all. ### Method Function call ### Endpoint `telemetry:span(EventPrefix, StartMetadata, Function)` ### Parameters - **EventPrefix** (list) - Required - Prefix for the event name. The actual events emitted are `EventPrefix ++ [start]`, `EventPrefix ++ [stop]`, and `EventPrefix ++ [exception]`. - **StartMetadata** (map) - Required - Metadata to include in the start event. - **Function** (function) - Required - Function to execute. Must return a tuple `{result, metadata}` on success. If it raises an exception, an exception event is emitted and the error is re-raised. ### Request Example In Elixir: ```elixir :telemetry.span( [:worker, :processing], %{message: message}, fn -> result = ... # Process the message {result, %{metadata: "Information related to the processing of the message"}} end ) ``` In Erlang: ```erlang telemetry:span( [worker, processing], #{message => Message}, fun() -> Result = % Process the message {Result, #{metadata => "Information related to the processing of the message"}} end ) ``` ### Response #### Success Response - **result** (any) - The result of the provided function. - **metadata** (map) - The metadata returned by the function, included in the stop event. #### Response Example No explicit response example provided. ### Notes - The start event measurements include a `system_time` key derived from `erlang:system_time/0`. - The stop and exception event measurements include a `duration` key derived from `erlang:monotonic_time() - StartMonotonicTime`. - All events include a `monotonic_time` measurement. - All time values are in native units. Convert duration using `System.convert_time_unit(duration, :native, :millisecond)`. ``` -------------------------------- ### Create span events with telemetry:span/3 (Erlang) Source: https://telemetry.hexdocs.pm/readme.html Erlang equivalent of the Elixir span example. The function must return a tuple {Result, Metadata}. The start_metadata map is passed as metadata for the start event. ```erlang process_message(Message) -> StartMetadata = #{message => Message}, Result = telemetry:span( [worker, processing], StartMetadata, fun() -> Result = % Process the message {Result, #{metadata => "Information related to the processing of the message"}} end ). ``` -------------------------------- ### Create span events with :telemetry.span/3 (Elixir) Source: https://telemetry.hexdocs.pm/readme.html Wraps a function with :telemetry.span/3 to emit start, stop, or exception events. The function must return a tuple {result, metadata}. The start_metadata is passed as metadata for the start event. ```elixir def process_message(message) do start_metadata = %{message: message} result = :telemetry.span( [:worker, :processing], start_metadata, fn -> result = ... # Process the message {result, %{metadata: "Information related to the processing of the message"}} end ) end ``` -------------------------------- ### span(EventPrefix, StartMetadata, SpanFunction) Source: https://telemetry.hexdocs.pm/telemetry.html Runs the provided SpanFunction, emitting start and stop/exception events, invoking the handlers attached to each. ```APIDOC ## span(EventPrefix, StartMetadata, SpanFunction) ### Description Runs the provided SpanFunction, emitting start and stop/exception events, invoking the handlers attached to each. ### Function Signature `span(EventPrefix, StartMetadata, SpanFunction)` ### Parameters - **EventPrefix** (event_prefix()) - Required - The prefix for the start and stop events. - **StartMetadata** (map()) - Required - Metadata for the start event. - **SpanFunction** (span_function()) - Required - The function to run within the span. ### Returns - The result of the SpanFunction. ``` -------------------------------- ### span/3 Source: https://telemetry.hexdocs.pm/telemetry.html Runs the provided SpanFunction, emitting start and stop/exception events, invoking the handlers attached to each. The SpanFunction must return a {result, stop_metadata} or {result, extra_measurements, stop_metadata} tuple. ```APIDOC ## span/3 ### Description Runs the provided `SpanFunction`, emitting start and stop/exception events, invoking the handlers attached to each. The `SpanFunction` must return a `{result, stop_metadata}` or a `{result, extra_measurements, stop_metadata}` tuple. ### Function Signature ```erlang -spec span(event_prefix(), event_metadata(), span_function()) -> span_result(). ``` ### Parameters - `EventPrefix` (list) - Required - The event name prefix, a list of atoms. The actual events emitted will be `EventPrefix ++ [start]` and `EventPrefix ++ [stop]` or `EventPrefix ++ [exception]`. - `StartMetadata` (map) - Required - Metadata to be included in the start event and merged with exception metadata if an exception occurs. - `SpanFunction` (function) - Required - The function to run. Must return `{result, stop_metadata}` or `{result, extra_measurements, stop_metadata}`. ### Return Value Returns the result of the `SpanFunction`. ### Events Emitted #### Start Event - Event: `EventPrefix ++ [start]` - Measurements: - `system_time` (integer) - Current system time in native units from `erlang:system_time()`. - `monotonic_time` (integer) - Current monotonic time. - Metadata: - `telemetry_span_context` (term) - Default span context added if not provided in `StartMetadata`. - User-defined metadata from `StartMetadata`. #### Stop Event - Event: `EventPrefix ++ [stop]` - Measurements: - `duration` (integer) - Monotonic time difference from start to stop. - `monotonic_time` (integer) - Current monotonic time. - User-defined extra measurements if `SpanFunction` returns a 3-element tuple. - Metadata: - `error` (term) - Optional error field if the stop event is the result of an error but not necessarily an exception. - `telemetry_span_context` (term) - Span context. - User-defined metadata from `StopMetadata`. #### Exception Event - Event: `EventPrefix ++ [exception]` - Measurements: - `duration` (integer) - Monotonic time difference from start to exception. - `monotonic_time` (integer) - Current monotonic time. - Metadata: - `kind` (atom) - `throw`, `error`, or `exit`. - `reason` (term) - The exception reason. - `stacktrace` (list) - The stacktrace. - `telemetry_span_context` (term) - Span context. - User-defined metadata from `StartMetadata` merged with exception metadata. ### Notes - The standard measurements `duration` and `monotonic_time` cannot be overridden. - It is highly recommended that `StopMetadata` includes all values from `StartMetadata` to simplify event handlers. - If the current process crashes due to an exit signal, none or only part of the events may be emitted. ``` -------------------------------- ### Attach to span events with telemetry:attach_many/4 (Erlang) Source: https://telemetry.hexdocs.pm/readme.html Erlang equivalent of the attach example. Uses a binary handler ID and a fun referencing log_response_handler:handle_event/4 with an empty list as configuration. ```erlang ok = telemetry:attach_many( <<"log-response-handler">>, [ [worker, processing, start], [worker, processing, stop], [worker, processing, exception] ], fun log_response_handler:handle_event/4, [] ) ``` -------------------------------- ### Define event handler module for span events (Elixir) Source: https://telemetry.hexdocs.pm/readme.html Defines LogResponseHandler module with handle_event/4 that logs the event, measurements, and metadata using Logger. This handler is referenced in the attach example. ```elixir defmodule LogResponseHandler do require Logger def handle_event(event, measurements, metadata, _config) do Logger.info("Event: #{inspect(event)}") Logger.info("Measurements: #{inspect(measurements)}") Logger.info("Metadata: #{inspect(metadata)}") end end ``` -------------------------------- ### Execute a telemetry event in Elixir Source: https://telemetry.hexdocs.pm/readme.html Executes a telemetry event with measurements and metadata. The event name is a list of atoms. This example is part of a workflow for logging request latency and status. ```elixir :telemetry.execute( [:web, :request, :done], %{latency: latency}, %{request_path: path, status_code: status} ) ``` -------------------------------- ### telemetry:span/3 Source: https://telemetry.hexdocs.pm/readme.html Generates a start event and a stop or exception event depending on whether the provided function executes successfully or raises an error. The function leverages telemetry:execute/3 and re-raises any caught errors. ```APIDOC ## telemetry:span/3 ### Description Generates a start event and a stop or exception event depending on whether the provided function executes successfully or raises an error. The function leverages telemetry:execute/3 and re-raises any caught errors. ### Function Signature `telemetry:span(EventPrefix, StartMetadata, Function)` ### Parameters - **EventPrefix** (list of atoms) - Required - The event name prefix. The start event will be `EventPrefix ++ [start]`, the stop event `EventPrefix ++ [stop]`, and the exception event `EventPrefix ++ [exception]`. - **StartMetadata** (map) - Required - Metadata included in the start event. - **Function** (function) - Required - The function to execute. It should return a tuple `{result, stop_metadata}` on success. If it raises an exception, an exception event is emitted and the error is re-raised. ### Events Emitted - `EventPrefix ++ [start]` - Emitted when the function starts. - `EventPrefix ++ [stop]` - Emitted when the function completes successfully. - `EventPrefix ++ [exception]` - Emitted when the function raises an exception. ### Measurements - For `start` events: `system_time` (derived from `erlang:system_time/0`), `monotonic_time`. - For `stop` and `exception` events: `duration` (derived from `erlang:monotonic_time() - StartMonotonicTime`), `monotonic_time`. - All times are in native units. ### Usage Example (Elixir) ```elixir def process_message(message) do start_metadata = %{message: message} result = :telemetry.span( [:worker, :processing], start_metadata, fn -> result = ... # Process the message {result, %{metadata: "Information related to the processing of the message"}} end ) end ``` ### Usage Example (Erlang) ```erlang process_message(Message) -> StartMetadata = #{message => Message}, Result = telemetry:span( [worker, processing], StartMetadata, fun() -> Result = % Process the message {Result, #{metadata => "Information related to the processing of the message"}} end ). ``` ### Attaching to Span Events (Elixir) ```elixir :ok = :telemetry.attach_many( "log-response-handler", [ [:worker, :processing, :start], [:worker, :processing, :stop], [:worker, :processing, :exception] ], &LogResponseHandler.handle_event/4, nil ) ``` ### Attaching to Span Events (Erlang) ```erlang ok = telemetry:attach_many( <<"log-response-handler">>, [ [worker, processing, start], [worker, processing, stop], [worker, processing, exception] ], fun log_response_handler:handle_event/4, [] ) ``` ### Event Handler Module (Elixir) ```elixir defmodule LogResponseHandler do require Logger def handle_event(event, measurements, metadata, _config) do Logger.info("Event: #{inspect(event)}") Logger.info("Measurements: #{inspect(measurements)}") Logger.info("Metadata: #{inspect(metadata)}") end end ``` ### Event Handler Module (Erlang) ```erlang -module(log_response_handler). -include_lib("kernel/include/logger.hrl"). handle_event(Event, Measurements, Metadata, _Config) -> ?LOG_INFO("Event: ~p", [Event]), ?LOG_INFO("Measurements: ~p", [Measurements]), ?LOG_INFO("Metadata: ~p", [Metadata]). ``` ### Duration Conversion To convert the duration from native units: ```elixir milliseconds = System.convert_time_unit(duration, :native, :millisecond) ``` ``` -------------------------------- ### Execute a telemetry event in Erlang Source: https://telemetry.hexdocs.pm/readme.html Executes a telemetry event with measurements and metadata in Erlang. The event name is a list of atoms. This example is part of a workflow for logging request latency and status. ```erlang telemetry:execute( [web, request, done], #{latency => Latency}, #{request_path => Path, status_code => Status} ) ``` -------------------------------- ### Attach to span events with :telemetry.attach_many/4 (Elixir) Source: https://telemetry.hexdocs.pm/readme.html Attaches a handler to the start, stop, and exception events emitted by :telemetry.span/3. The handler is LogResponseHandler.handle_event/4 with nil as the configuration. ```elixir :ok = :telemetry.attach_many( "log-response-handler", [ [:worker, :processing, :start], [:worker, :processing, :stop], [:worker, :processing, :exception] ], &LogResponseHandler.handle_event/4, nil ) ``` -------------------------------- ### list_handlers(EventPrefix) Source: https://telemetry.hexdocs.pm/telemetry.html Returns all handlers attached to events with the given prefix. Handlers attached to many events at once using attach_many/4 will be listed once for each event they're attached to. An empty list returns all handlers. ```APIDOC ## list_handlers(EventPrefix) ### Description Returns all handlers attached to events with the given prefix. Handlers attached to many events at once using attach_many/4 will be listed once for each event they're attached to. An empty list returns all handlers. ### Function Signature ```erlang -spec list_handlers(event_prefix()) -> [handler()]. ``` ### Parameters - **EventPrefix** (event_prefix()) - Required - The prefix of events to list handlers for. Use an empty list to list all handlers. ### Returns - **list of handler()** - The list of handlers attached to events with the given prefix. ### Notes - Handlers attached to many events at once using `attach_many/4` will be listed once for each event they're attached to. - You can list all handlers by feeding this function an empty list. ``` -------------------------------- ### execute(EventName, Measurements, Metadata) Source: https://telemetry.hexdocs.pm/telemetry.html Emits an event with the given name, measurements, and metadata, invoking all handlers attached to the event. The handler function is called with four arguments: event name, measurements map, metadata map, and handler configuration. ```APIDOC ## execute(EventName, Measurements, Metadata) ### Description Emits an event with the given name, measurements, and metadata, invoking all handlers attached to the event. The handler function is called with four arguments: event name, measurements map, metadata map, and handler configuration. ### Function Signature ```erlang -spec execute(EventName, Measurements, Metadata) -> ok when EventName :: event_name(), Measurements :: event_measurements() | event_value(), Metadata :: event_metadata(). ``` ### Parameters - **EventName** (event_name()) - Required - The name of the event to emit. - **Measurements** (event_measurements() | event_value()) - Required - The measurements associated with the event. - **Metadata** (event_metadata()) - Required - The metadata associated with the event. ### Returns - **ok** - Indicates the event was emitted successfully. ### Handler Invocation When the event is emitted, the handler function provided to `attach/4` is called with four arguments: - the event name - the map of measurements - the map of event metadata - the handler configuration given to `attach/4` ### Best Practices While you are able to emit messages of any `event_name/0` structure, it is recommended that you follow the guidelines laid out in `span/3` if you are capturing start/stop events. ``` -------------------------------- ### execute(EventName, Measurements, Metadata) Source: https://telemetry.hexdocs.pm/telemetry.html Emits an event with the given measurements and metadata, invoking all handlers attached to the event. ```APIDOC ## execute(EventName, Measurements, Metadata) ### Description Emits the event, invoking handlers attached to it. The handlers are called with the provided measurements and metadata. ### Function Signature `execute(EventName, Measurements, Metadata)` ### Parameters - **EventName** (event_name()) - Required - The event to emit. - **Measurements** (event_measurements()) - Required - A map of measurements for the event. - **Metadata** (event_metadata()) - Required - A map of metadata for the event. ### Returns - `:ok` - always. ``` -------------------------------- ### execute(EventName, Measurements) Source: https://telemetry.hexdocs.pm/telemetry.html Emits an event with the given measurements and empty metadata, invoking all handlers attached to the event. ```APIDOC ## execute(EventName, Measurements) ### Description Same as `execute(EventName, Measurements, #{})`. Emits the event, invoking handlers attached to it. ### Function Signature `execute(EventName, Measurements)` ### Parameters - **EventName** (event_name()) - Required - The event to emit. - **Measurements** (event_measurements()) - Required - A map of measurements for the event. ### Returns - `:ok` - always. ``` -------------------------------- ### list_handlers(EventPrefix) Source: https://telemetry.hexdocs.pm/telemetry.html Returns all handlers attached to events with the given prefix. ```APIDOC ## list_handlers(EventPrefix) ### Description Returns all handlers attached to events with the given prefix. ### Function Signature `list_handlers(EventPrefix)` ### Parameters - **EventPrefix** (event_prefix()) - Required - The prefix of the events to list handlers for. ### Returns - A list of `{event_name, handler_id, function, config}` tuples. ``` -------------------------------- ### execute(EventName, Measurements) Source: https://telemetry.hexdocs.pm/telemetry.html Emits an event with the given name and measurements, using empty metadata. This is equivalent to calling execute(EventName, Measurements, #{}) and invokes all handlers attached to the event. ```APIDOC ## execute(EventName, Measurements) ### Description Emits an event with the given name and measurements, using empty metadata. This is equivalent to calling execute(EventName, Measurements, #{}) and invokes all handlers attached to the event. ### Function Signature ```erlang -spec execute(EventName, Measurements) -> ok when EventName :: event_name(), Measurements :: event_measurements() | event_value(). ``` ### Parameters - **EventName** (event_name()) - Required - The name of the event to emit. - **Measurements** (event_measurements() | event_value()) - Required - The measurements associated with the event. ### Returns - **ok** - Indicates the event was emitted successfully. ### Notes - Equivalent to `execute(EventName, Measurements, #{})`. ``` -------------------------------- ### Add Telemetry dependency in mix.exs Source: https://telemetry.hexdocs.pm/readme.html Adds the Telemetry library to a Mix project's dependencies. Use this in the deps/0 function of mix.exs. ```elixir defp deps() do [ {:telemetry, "~> 1.0"} ] end ``` -------------------------------- ### Define event handler module for span events (Erlang) Source: https://telemetry.hexdocs.pm/readme.html Erlang equivalent of the handler module. Uses the kernel logger macro ?LOG_INFO to log event, measurements, and metadata. ```erlang -module(log_response_handler). -include_lib("kernel/include/logger.hrl"). handle_event(Event, Measurements, Metadata, _Config) -> ?LOG_INFO("Event: ~p", [Event]), ?LOG_INFO("Measurements: ~p", [Measurements]), ?LOG_INFO("Metadata: ~p", [Metadata]). ``` -------------------------------- ### execute_lazy/3 Source: https://telemetry.hexdocs.pm/telemetry.html Emits an event with a lazy function that provides measurements and metadata, with additional arguments. This function is documented but the source does not provide further details. ```APIDOC ## execute_lazy/3 ### Description Emits an event with a lazy function that provides measurements and metadata, with additional arguments. This function is documented but the source does not provide further details. ### Parameters - **EventName** (event_name()) - Required - The name of the event to emit. - **Func** (function) - Required - A function that returns measurements and metadata. - **Additional arguments** - Required - Additional arguments for the lazy function. ### Returns - **ok** - Indicates the event was emitted successfully. ``` -------------------------------- ### Add Telemetry dependency in rebar.config Source: https://telemetry.hexdocs.pm/readme.html Adds the Telemetry library to a Rebar3 project's dependencies. Use this in the rebar.config file. ```erlang {deps, [{telemetry, "~> 1.0"}]}. ``` -------------------------------- ### persist() Source: https://telemetry.hexdocs.pm/telemetry.html Persists telemetry handlers. This is used to ensure handlers are stored in a durable way. ```APIDOC ## persist() ### Description Persist telemetry handlers. This is used to ensure handlers are stored in a durable way. ### Function Signature `persist()` ### Parameters None. ### Returns - `:ok` - always. ``` -------------------------------- ### Define a telemetry event handler in Elixir Source: https://telemetry.hexdocs.pm/readme.html Defines a module with a handle_event/4 callback that logs request latency and status. The callback is invoked synchronously on each telemetry:execute call, so avoid blocking operations. ```elixir defmodule LogResponseHandler do require Logger def handle_event([:web, :request, :done], measurements, metadata, _config) do Logger.info( "[#{metadata.request_path}] #{metadata.status_code} sent in #{measurements.latency}" ) end end ``` -------------------------------- ### attach(HandlerId, EventName, Function, Config) Source: https://telemetry.hexdocs.pm/telemetry.html Attaches a handler to a specific event. When the event is executed, the handler function is invoked with the event measurements and metadata. ```APIDOC ## attach(HandlerId, EventName, Function, Config) ### Description Attaches the handler to the event. When the event is emitted, the handler function is invoked. ### Function Signature `attach(HandlerId, EventName, Function, Config)` ### Parameters - **HandlerId** (term) - Required - Unique identifier for the handler. - **EventName** (event_name()) - Required - The event to attach to. - **Function** (handler_function()) - Required - The function to invoke when the event is emitted. - **Config** (handler_config()) - Required - Configuration passed to the handler function. ### Returns - `:ok` - if the handler was successfully attached. - `{:error, :already_exists}` - if a handler with the same HandlerId is already attached. ``` -------------------------------- ### execute_lazy/3 Source: https://telemetry.hexdocs.pm/telemetry.html Executes an event with lazy measurements and metadata, allowing separate functions for measurements and metadata. ```APIDOC ## execute_lazy/3 ### Description Executes an event with lazy measurements and metadata. The functions are called to generate the measurements and metadata only if there are handlers attached. ### Function Signature `execute_lazy(EventName, MeasurementsFunc, MetadataFunc)` ### Parameters - **EventName** (event_name()) - Required - The event to emit. - **MeasurementsFunc** (function) - Required - A zero-arity function that returns the measurements map. - **MetadataFunc** (function) - Required - A zero-arity function that returns the metadata map. ### Returns - `:ok` - always. ``` -------------------------------- ### execute_lazy(EventName, Func) Source: https://telemetry.hexdocs.pm/telemetry.html Emits an event with a lazy function that provides measurements and metadata. This function is documented but the source does not provide further details. ```APIDOC ## execute_lazy(EventName, Func) ### Description Emits an event with a lazy function that provides measurements and metadata. This function is documented but the source does not provide further details. ### Parameters - **EventName** (event_name()) - Required - The name of the event to emit. - **Func** (function) - Required - A function that returns measurements and metadata. ### Returns - **ok** - Indicates the event was emitted successfully. ``` -------------------------------- ### attach(HandlerId, EventName, Function, Config) Source: https://telemetry.hexdocs.pm/telemetry.html Attaches a handler to an event. The handler ID must be unique; otherwise, an error is returned. Handlers are executed by the dispatching process, and failures result in handler removal and a failure event. ```APIDOC ## attach(HandlerId, EventName, Function, Config) ### Description Attaches the handler to the event. The `HandlerId` must be unique; if another handler with the same ID already exists, the `{error, already_exists}` tuple is returned. Handlers are executed by the process dispatching the event, and the order of invocation is not guaranteed. ### Method Function call ### Endpoint attach/4 ### Parameters - **HandlerId** (handler_id()) - Required - Unique identifier for the handler. - **EventName** (event_name()) - Required - The event name to attach the handler to. - **Function** (handler_function()) - Required - The function to be called when the event is emitted. Should be a function capture for best performance. - **Config** (handler_config()) - Required - Configuration term passed to the handler function. ### Returns - `ok` - Handler attached successfully. - `{error, already_exists}` - A handler with the same ID already exists. ### Handler Failure Events When a handler fails, it is removed and a failure event is emitted with the following details: - Event name: `[telemetry, handler, failure]` - Measurements: - `monotonic_time` - Current monotonic time in native units. - `system_time` - Current system time in native units. - Metadata: - `event_name` - The event that failed. - `handler_id` - The ID of the failed handler. - `handler_config` - The configuration of the failed handler. - `kind` - The kind of failure (`error`, `exit`, `throw`). - `reason` - The reason for the failure. - `stacktrace` - The stacktrace for the failure. These failure events should only be used for monitoring and diagnostic purposes. ``` -------------------------------- ### Define a telemetry event handler in Erlang Source: https://telemetry.hexdocs.pm/readme.html Defines a module with a handle_event/4 callback that logs request latency and status using the logger. The callback is invoked synchronously on each telemetry:execute call, so avoid blocking operations. ```erlang -module(log_response_handler). -include_lib("kernel/include/logger.hrl"). handle_event([web, request, done], #{latency := Latency}, #{request_path := Path, status_code := Status}, _Config) -> ?LOG_INFO("[~s] ~p sent in ~p", [Path, Status, Latency]). ``` -------------------------------- ### attach_many(HandlerId, EventNames, Function, Config) Source: https://telemetry.hexdocs.pm/telemetry.html Attaches a handler to multiple events. The handler function is invoked when any of the specified events are emitted. ```APIDOC ## attach_many(HandlerId, EventNames, Function, Config) ### Description Attaches the handler to many events. The handler function is invoked when any of the specified events are emitted. ### Function Signature `attach_many(HandlerId, EventNames, Function, Config)` ### Parameters - **HandlerId** (term) - Required - Unique identifier for the handler. - **EventNames** ([event_name()]) - Required - List of events to attach to. - **Function** (handler_function()) - Required - The function to invoke when any of the events are emitted. - **Config** (handler_config()) - Required - Configuration passed to the handler function. ### Returns - `:ok` - if the handler was successfully attached. - `{:error, :already_exists}` - if a handler with the same HandlerId is already attached. ```