Elixir foundationSort Order

Elixir: Setup Logging and Code Reloading - [005]

We'll need code reloading if we're going to be productive so let's set that up. We'll use a hex package called remix.

Code Reloading

In mix.exs let's add our package.

defp deps do  # ...  # Development.   {:remix, "~> 0.0.2", only: :dev}end

We'll also need to setup which applications to load based on the environment. We want to run the :remix package only in development.

def application do  [    extra_applications: applications(Mix.env),    mod: {Botiful.Application, []}  ]enddefp applications(:dev), do: applications(:all) ++ [:remix]defp applications(_all), do: [:cowboy, :plug, :logger]

This will only add :remix to the extra_applications when Mix.env returns :dev


Let's setup some basic logging for our lib/botiful/application.ex . We'll use the Logger module already included in our application by default.

require Logger@port 8080def start(_type, _args) do  # List all child processes to be supervised  children = [    {Plug.Adapters.Cowboy2, scheme: :http, plug: Botiful, options: [port: @port]}    # Starts a worker by calling: Botiful.Worker.start_link(arg)    # {Botiful.Worker, arg},  ]  Logger.info("Listening on #{@port}...")  # See https://hexdocs.pm/elixir/Supervisor.html  # for other strategies and supported options  opts = [strategy: :one_for_one, name: Botiful.Supervisor]  Supervisor.start_link(children, opts)end

We move our port to a module attribute @port since we're going to reference it a couple of times. We then call the Logger module to log out a message when it's starting up our application.

Logging Web Request

We also need to add logging capability to our router. This can be done very easily by adding the Plug.Logging module to our router. In lib/botiful.ex

defmodule Botiful do  # ...  use Plug.Router    # Add the following  plug Plug.Logger    plug :match  plug :dispatch    # ...end

This will now log web requests in our console.