Skip to content

Instantly share code, notes, and snippets.

@cheerfulstoic
Last active July 15, 2021 19:46
Show Gist options
  • Save cheerfulstoic/9498a7f262ffc5a12b5ec87be8db2590 to your computer and use it in GitHub Desktop.
Save cheerfulstoic/9498a7f262ffc5a12b5ec87be8db2590 to your computer and use it in GitHub Desktop.
Emoji Game - Telemetry Example
# lib/emoji_game/actor.ex
# Non-player character client
defmodule EmojiGame.Actor do
use GenServer
# ... code ...
@impl true
def handle_info(:move, {x, y}) do
new_x = x + Enum.random(@move_shift_amounts)
new_y = y + Enum.random(@move_shift_amounts)
:telemetry.span(
[:emoji_game, :actor, :move_time],
%{},
fn ->
{EmojiGame.Game.move({new_x, new_y}), %{}}
end
)
Process.send_after(self(), :move, 1_000)
{:noreply, {new_x, new_y}}
end
end
# lib/emoji_game/game.ex
# Game server
defmodule EmojiGame.Game do
use GenServer
# ... code ...
@impl true
def handle_call({:move, new_position}, {from_pid, _}, state) do
# Will this cause problems in responding?
report_metrics()
# `move` message handling code
end
# ... code ...
# Helpers
def report_metrics do
pid = Process.whereis(__MODULE__)
{:message_queue_len, length} = Process.info(pid, :message_queue_len)
:telemetry.execute(
[:emoji_game, :game, :queue],
%{length: length},
%{ }
)
end
end
# lib/emoji_game_web/telemetry.ex
# Phoenix Configuration for Telemetry
defmodule EmojiGameWeb.Telemetry do
use Supervisor
import Telemetry.Metrics
# ... Phoenix scaffold code ...
def metrics do
[
# Game Metrics
summary("emoji_game.game.queue.length"),
summary("emoji_game.actor.move_time.stop.duration", unit: {:native, :millisecond}),
# ... Phoenix scaffold code ...
]
end
def metrics_statsd_options do
[
metrics: [
summary("emoji_game.game.queue.length"),
summary("emoji_game.actor.move_time.stop.duration", unit: {:native, :millisecond}),
]
]
end
# ... Phoenix scaffold code ...
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment