Timber Plug v1.1.0 Timber.Plug.Event View Source

Automatically logs metadata information about HTTP requests and responses in Plug-based frameworks like Phoenix.

Whether you use Plug by itself or as part of a framework like Phoenix, adding this plug to your pipeline will automatically create events for incoming HTTP requests and responses for your log statements.

Note: If you’re using Timber.Plug.HTTPContext, that plug should come before Timber.Plug.Event in any pipeline. This will give you the best results.

Adding the Plug

Timber.Plug.Event can be added to your plug pipeline using the standard Plug.Builder.plug/2 macro. The point at which you place it determines what state Timber will receive the connection in, therefore it’s recommended you place it as close to the origin of the request as possible.

Plug (Standalone or Plug.Router)

If you are using Plug without a framework, your setup will vary depending on your architecture. The call to plug Timber.Plug.Event should be grouped with any other plugs you call prior to performing business logic.

Timber expects query paramters to have already been fetched on the connection using Plug.Conn.fetch_query_params/2.

Phoenix

Phoenix’s flexibility means there are multiple points in the plug pipeline where the Timber.Plug.Event can be inserted. The recommended place is in a :logging pipeline in your router, but if you have more complex needs you can also place the plug in an endpoint or a controller.

defmodule MyApp.Router do
  use MyApp.Web, :router

  pipeline :logging do
    plug Timber.Plug.Event
  end

  scope "/api", MyApp do
    pipe_through :logging
  end
end

If you place the plug call in your endpoint, you will need to make sure that it appears after Plug.RequestId (if you are using it) but before the call to your router.

Issues with Plug.ErrorHandler

If you are using Plug.ErrorHandler, you will not see a response event if an exception is raised. This is because of how the error handler works in practice. In order to capture information about the response, Timber registers a callback to be used before Plug actually sends the response. Plug stores this information on the connection struct. When an exception is raised, the methodology used by the error handler will reset the conn to the state it was first accepted by the router.

Link to this section Summary

Link to this section Functions

Link to this function full_url(scheme, host, path, port, query_string) View Source
Link to this function headers_to_headers_json(headers) View Source
headers_to_headers_json(Keyword.t()) :: String.t()