gmile

gmile

Gathering runtime statistics about function calls across entire app

How does one approach gathering runtime statistics about function calls from modules that belong to a specific app?

In my app, using a combination of decorator and telemetry packages, I am able to collect statistics about function calls like this:

defmodule MyApp.FunctionTracing do
  use Decorator.Define, span: 0

  def span(body, context) do
    quote do
      metadata = %{
        function: "#{unquote(context.module)}.#{unquote(context.name)}/#{unquote(length(context.args))}"
      }

      :telemetry.span([:my_app, :function_call], metadata, fn ->
        {unquote(body), metadata}
      end)
    end
  end
end

defmodule MyApp.MyModule do
  use MyApp.FunctionTracing

  @decorate span()
  def create_session(args) do
    # ...
  end
end

This is then exposed via a family of telemetry packages in a form of GET /metrics endpoint for Prometheus collector to come and pick up.

I can do the above manually for functions that I suspect may not be called. Could someone think of a way to scale this approach? E.g. is there a way I could tell Elixir compiler: please, when compiling ALL modules that belong to my own app, do wrap them in such a way?

The end goal here is to highlight & eliminate dead from from a fairly large codebase. Having all functions instrumented this way, I’d deploy the code in staging or production, collect the statistics for a week or two, then use it to base decisions about code clean up.

Or is this too crazy of a thing to want for such a use case? :slight_smile: If it’s too crazy, what would be a good alternative?

I’ve heard one could go a long way with tools already available in Erlang VM / stdlib for tracing and such, - if so, could someone point me in the right direction? At this point all I’m interested in is just counting all function calls coming from modules that belong to my own app.

Ideally, after a week or two of “counting”, I could filter out all function calls with 0 calls, and begin cleaning up the code.

Marked As Solved

voltone

voltone

This may be relatively safe in production:

On application startup, call :erlang.trace_pattern({:_, :_, :_}, true, [:call_count]). If code loading is dynamic (i.e. you’re not running as part of a release), also call :erlang.trace_pattern(:on_load, true, [:call_count]).

Then whenever you want to gather call stats for all public functions that have been called at least once:

for {m, _} <- :code.all_loaded(),
    {f, a} <- m.module_info(:functions),
    {:call_count, c} = :erlang.trace_info({m, f, a}, :call_count),
    c > 0,
  do: {{m, f, a}, c}   # or if you prefer: {"#{inspect(m)}.#{f}/#{a}", c}

If you want to include functions that were never called, just drop the c > 0, line.

Or, for your use-case of finding unused functions in a given application:

app = :my_app
for m <-  Application.spec(app)[:modules],
    {f, a} <- m.module_info(:functions),
    {:call_count, c} = :erlang.trace_info({m, f, a}, :call_count),
    c == 0,
  do: {{m, f, a}, c}   # or if you prefer: {"#{inspect(m)}.#{f}/#{a}", c}

In that case you can also selectively enable call count tracing for only the modules of your application, instead of for all modules in the system.

You can reset the counters with :erlang.trace_pattern({:_, :_, :_}, :restart, [:call_count]) or stop tracing with :erlang.trace_pattern({:_, :_, :_}, false, [:call_count]).

Also Liked

LostKobrakai

LostKobrakai

And this is a much more practical introduction: Debugging With Tracing in Elixir
For elixir I suggest Extrace to also get elixir syntax for traces.

al2o3cr

al2o3cr

This article discusses the BEAM’s tracing machinery and some of the Elixir wrappers available.

Where Next?

Popular in Questions Top

electic
Hi, I am new to Elixir. I am trying to use the DateTime component to insert a date into MySQL however the there seems to be no way to fo...
New
joaquinalcerro
Hi there, I am working with Ecto-Postgresql and I need to call all of the records from a specific table but the table has 40,000 records...
New
_russellb
I want to try my hand at web scraping. What tools/libraries do I need to use. I’m hoping to turn this into something professional so don’...
New
hariharasudhan94
lets say i have a sample like a = 20; b = 10; if (a &gt; b) do {:ok, "a"} end if (a &lt; b) do {:ok, b} end if (a == b) do {:ok, "equa...
New
JulienCorb
I am trying to implement my new.html.eex file to create new posts on my website. new.html.eex: &lt;h1&gt;Create Post&lt;/h1&gt; &lt;%= ...
New
ashish173
I am using Ecto timestamps with postgres, I can see the timestamps() use the :naive_dateime but for my use case I wanted to store the ti...
New
chensan
I have a User schema with a :from_id field set to type :string: defmodule TweetBot.Repo.Migrations.CreateUsers do use Ecto.Migration ...
New
9mm
I am constructing a JSON object (map) and I need to conditionally set a field. I’m trying to write proper elixir-way code… and I’m at a l...
New
jerry
Good day to you all. I have been struggling to get a query involving like and ilike to work. Can anyone assist me on this, please? pro...
New
aalberti333
As the title describes, I’m trying to run Enum.map() over a list of key/value pairs, where the value is a map. My data looks like this: ...
New

Other popular topics Top

rms.mrcs
Hi, I need to transform a list of numbers into a map where the keys are the indexes and the values are the original values of the list. ...
New
electic
Hi, I am new to Elixir. I am trying to use the DateTime component to insert a date into MySQL however the there seems to be no way to fo...
New
nobody
Hi! In PHP: $_SERVER[‘SERVER_ADDR’] - in Elixir? Searched the docs for ip address and the web, no good results. Thanks!
New
jaysoifer
Is there a way to rollback a specific migration and only that one (“skipping” all the other ones)? Would mix ecto.rollback -v 200809061...
New
jononomo
I am trying to figure out how Mix knows whether the environment is test, dev, or prod – where is this set? Thanks.
New
chrismccord
As promised, the first release candidate of Phoenix 1.3.0 is out! This release focuses on code generators with improved project structure...
New
Brian
What is the proper way to load a module from a file in to IEX? In the python world, doing something like this pretty standard: from ....
New
Lily
In templates/appointment/index.html.eex: &lt;%= for appointment &lt;- @appointments do %&gt; &lt;tr&gt; &lt;td&gt;&lt;%= appoi...
New
dogweather
I wrote this comment on r/haskell, and it’s not popular there. :wink: But I think I’m on to something… Haskell reminds me of Java, and e...
New
jason.o
In the code below, if the create action is not set to accept “extra_key” as an input, it errors out with a message shown above. Is there ...
New

Latest on Elixir Forum

We're in Beta

About us Mission Statement