Skip to content

Instantly share code, notes, and snippets.

@paulo-ferraz-oliveira
Created May 5, 2023 13:17
Show Gist options
  • Save paulo-ferraz-oliveira/ba66dcee1ef2e0d92922eba236062b3e to your computer and use it in GitHub Desktop.
Save paulo-ferraz-oliveira/ba66dcee1ef2e0d92922eba236062b3e to your computer and use it in GitHub Desktop.
Wrap a function in a "timed-performance" log decorator, using Elixir library decorator and Logger

Here's an example of how to do it.

def with_performance_log(options, body, context) do
  quote bind_quoted: [
          context: Macro.escape(context),
          options: Macro.escape(options),
          body: body
        ] do
    module = "#{context.module}"
    function = "#{context.name}/#{context.arity}"

    level = options[:level] || :debug
    message = options[:message] || "undefined"
    metadata = options[:metadata] || []

    {time_us, value} = :timer.tc(fn -> body end)

    metadata =
      [
        module: module,
        function: function,
        time_us: time_us
      ] ++ metadata

    Logger.bare_log(level, message, metadata)

    value
  end
end

Documentation for the library can be checked at https://hexdocs.pm/decorator/readme.html.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment