How to log malformed requests which cause cowboy to terminate request?

So answering to my own question:

I don’t know why Plug.Cowboy doesn’t show 431 via Logger as it should in handle_event/4 but if I manually attach a telemetry handler to the [:cowboy, :request, :early_error] event then I can get logs. Even though they not the logs I need (I would prefer to have the full initial request to analyze what exactly cowboy didn’t like) but better than total silence.

So just make put a handler somewhere:

defmodule MyAppWeb.CowboyLogger do
  @moduledoc false

  require Logger

  def init do
    :telemetry.attach(
      :my_app_cowboy_logger,
      [:cowboy, :request, :early_error],
      &handle_event/4,
      nil
    )
  end

  def handle_event(
        [:cowboy, :request, :early_error],
        _,
        req,
        _
      ) do
    Logger.error("cowboy error: #{inspect(req)}")
  end
end

and then just call somewhere MyAppWeb.CowboyLogger.init(), for example, from MyAppWeb.Telemetry.init/1.

But actually its pretty weird that Plug.Cowboy.handle_event/4 doesn’t work and no errors are shown.

2 Likes