Moesif API Elixir Plug

Overview

The Moesif API Elixir Plug is a sophisticated API monitoring and analytics tool tailored for Elixir and Phoenix applications. It provides deep insights into API usage, enabling you to understand customer interactions, monitor for issues, enforce API usage policies, and implement usage-based billing solutions. This integration facilitates seamless logging and analysis of high-volume API traffic without significant latency.

Features

Moesif API Elixir Plug enables your application to:

Installation

  1. Add Moesif API Elixir Plug to your list of dependencies in mix.exs:

    def deps do
      [
        {:moesif_api, "~> 0.2.0"}
      ]
    end
  2. Fetch the dependency by running mix deps.get.

Usage

Check out the example application at https://github.com/Moesif/moesif-elixir-phoenix-quickstart

  1. Add the Plug to your Phoenix endpoint or router in endpoint.ex:

    plug MoesifApi.Plug.EventLogger, [
      get_user_id: &ExampleApp.get_user_id/1,
      get_company_id: &ExampleApp.get_company_id/1
    ]
  2. Configure the Plug in as the example below. Replace Your Moesif Application Id with your Moesif application ID. The others are optional with production defaults.

    config :moesif_api, :config,
       application_id: "Your Moesif Application Id",
       event_queue_size: 100_000,
       max_batch_size: 100,
       max_batch_wait_time_ms: 2_000,
       raw_request_body_key: :raw_body,
  3. If you are using Parsers, you need to use MoesifApi.CacheBodyReader to cache the request body. Add the following to your endpoint.ex:

    plug Plug.Parsers,
      parsers: [:urlencoded, :json],
      pass: ["text/*"],
      body_reader: {MoesifApi.CacheBodyReader, :read_body, []},
      json_decoder: Jason

Using CacheBodyReader for Request Body Caching

When using parsers that read the request body, such as for JSON or URL-encoded data, it's crucial to ensure the Moesif API Elixir Plug can also access the request body for logging. This is where MoesifApi.CacheBodyReader, a custom reader for Plug.Parsers, comes into play.

Accessing Cached Body

After setting up CacheBodyReader, you can access the cached body with the configured key (default :raw_body) in your controllers or other plugs, as required:

def your_function(conn, _params) do
  cached_body = conn.assigns[:raw_body]  # Use the configured key if different
end

Configuration

Identifying Users and Companies

Troubleshooting

Support

For support and contributions, please raise issues or submit pull requests on our GitHub repository. For more comprehensive documentation, visit Moesif Documentation.