Tesla.Middleware.Logger (tesla v1.4.3) View Source

Log requests using Elixir's Logger.

With the default settings it logs request method, URL, response status, and time taken in milliseconds.

Examples

defmodule MyClient do
  use Tesla

  plug Tesla.Middleware.Logger
end

Options

  • :log_level - custom function for calculating log level (see below)
  • :filter_headers - sanitizes sensitive headers before logging in debug mode (see below)
  • :debug - show detailed request/response logging

Custom log format

The default log format is "$method $url -> $status ($time ms)" which shows in logs like:

2018-03-25 18:32:40.397 [info]  GET https://bitebot.io -> 200 (88.074 ms)

Because log format is processed during compile time it needs to be set in config:

config :tesla, Tesla.Middleware.Logger, format: "$method $url ====> $status / time=$time"

Custom log levels

By default, the following log levels will be used:

  • :error - for errors, 5xx and 4xx responses
  • :warn - for 3xx responses
  • :info - for 2xx responses

You can customize this setting by providing your own log_level/1 function:

defmodule MyClient do
  use Tesla

  plug Tesla.Middleware.Logger, log_level: &my_log_level/1

  def my_log_level(env) do
    case env.status do
      404 -> :info
      _ -> :default
    end
  end
end

Logger Debug output

When the Elixir Logger log level is set to :debug Tesla Logger will show full request & response.

If you want to disable detailed request/response logging but keep the :debug log level (i.e. in development) you can set debug: false in your config:

# config/dev.local.exs
config :tesla, Tesla.Middleware.Logger, debug: false

Note that the logging configuration is evaluated at compile time, so Tesla must be recompiled for the configuration to take effect:

mix deps.clean --build tesla
mix deps.compile tesla

In order to be able to set :debug at runtime we can pass it as a option to the middleware at runtime.

def client do
  middleware = [
    # ...
    {Tesla.Middleware.Logger, debug: false}
  ]

  Tesla.client(middleware)
end

Filter headers

To sanitize sensitive headers such as authorization in debug logs, add them to the :filter_headers option. :filter_headers expects a list of header names as strings.

# config/dev.local.exs
config :tesla, Tesla.Middleware.Logger,
  filter_headers: ["authorization"]

Link to this section Summary

Link to this section Types

Specs

log_level() :: :info | :warn | :error

Link to this section Functions

Specs

default_log_level(Tesla.Env.t()) :: log_level()