defmodule Timber.Phoenix do @moduledoc """ Handles instrumentation of `Phoenix.Endpoint`. This module is designed to log events when Phoenix calls a controller or renders a template. It hooks into the instrumentation tools built into Phoenix. Because of this, you will have to trigger a Phoenix recompile in order for the instrumentation to take effect. ## Adding Instrumentation Phoenix instrumenetation is controlled through the configuration for your Phoenix endpoint module, typically named along the lines of `MyApp.Endpoint`. This module will be configured in `config/config.exs` similar to the following: ``` config :my_app, MyApp.Endpoint, http: [port: 4001], root: Path.dirname(__DIR__), pubsub: [name: MyApp.PubSub, adapter: Phoenix.PubSub.PG2] ``` You will need to add an `:instrumenters` key to this configuration with a value of `[Timber.Phoenix]`. This would update the configuration to something like the following: ``` config :my_app, MyApp.Endpoint, http: [port: 4001], root: Path.dirname(__DIR__), instrumenters: [Timber.Phoenix], pubsub: [name: MyApp.PubSub, adapter: Phoenix.PubSub.PG2] ``` In order for this to take affect locally, you will need to recompile Phoenix using the command `mix deps.compile phoenix`. By default, Timber will log calls to controllers and template renders at the `:info` level. You can change this by adding an additional configuration line: ``` config :timber_phoenix, :instrumentation_level, :debug ``` If you're currently displaying logs at the `:debug` level, you will also see that Phoenix has built-in logging already at this level. The Phoenix logger will not emit Timber events, so you can turn it off to stop the duplicate output. The Phoenix logger is controlled through the `MyApp.Web` module. Look for a definition block like the following: ``` def controller do quote do use Phoenix.Controller end end ``` You will want to modify this to the following ``` def controller do quote do use Phoenix.Controller, log: false end end ``` ## Ignoring Controller Actions for Instrumentation If you have specific controller actions that you don't want to be instrumented, you can add them to the instrumentation blacklist. For example, if your application provides a health controller for external applications, you may want to stop instrumentation on that controller's actions to reduce noise. The `:parsed_controller_actions_blacklist` configuration key can be used to control which controller actions to suppress instrumentation for. It takes a list of two-element tuples. The first element is the controller name, and the second element is the action. If you would like to blacklist a specific controller or action, nil can be used as a wildcard. As an example, here's how we would prevent instrumentation of the `:check` action in `TimberClientAPI.HealthController` and every action in the PostController: ```elixir config :timber_phoenix, parsed_controller_actions_blacklist: MapSet.new([ {TimberClientAPI.HealthController, :check} {TimberClientAPI.PostController, nil} ]) ``` Now, when Phoenix calls `check/2` on the `TimberClientAPI.HealthController` module, no log lines will be produced! _Note_: If you're on a version of Phoenix prior to 1.3, you will still see logs for render events even if the controller is blacklisted. """ alias Timber.JSON require Logger @default_log_level :info @typep controller :: module @typep action :: atom @typep controller_action :: {controller, action} @typep parsed_blacklist :: MapSet.t(controller_action) @doc """ Gets the log level for logs generated by this instrumentation """ @spec get_log_level() :: Logger.level() def get_log_level() do Application.get_env(:timber_phoenix, :instrumentation_level, @default_log_level) end @doc """ Sets the log level for logs generated by this instrumentation """ @spec put_log_level(Logger.level()) :: :ok def put_log_level(level) do Application.put_env(:timber_phoenix, :instrumentation_level, level) end @doc """ Adds a controller action to the blacklist This function will update the blacklist of controller actions, following the same conventions as the blacklist described in the application configuration. The `controller` should be the qualified name of the Phoenix controller's Elixir module (e.g., `TimberClientAPI.OrganizationController`). The `action` should be the name of the action (e.g., `:index`). """ @spec add_controller_action_to_blacklist(controller, action) :: :ok def add_controller_action_to_blacklist(controller, action) do controller_action = {controller, action} blacklist = get_parsed_blacklist() new_blacklist = MapSet.put(blacklist, controller_action) put_parsed_blacklist(new_blacklist) end @doc """ Blacklists an entire controller This function will update the blacklist of controller actions, following the same conventions as the blacklist described in the application configuration. The `controller` should be the qualified name of the Phoenix controller's Elixir module (e.g., `TimberClientAPI.OrganizationController`). """ @spec add_controller_to_blacklist(controller) :: :ok def add_controller_to_blacklist(controller) do add_controller_action_to_blacklist(controller, nil) end @doc """ Blacklists an action regardless of the controller This function will update the blacklist of controller actions, following the same conventions as the blacklist described in the application configuration. The `action` should be the name of the action (e.g., `:index`). """ @spec add_action_to_blacklist(controller) :: :ok def add_action_to_blacklist(action) do add_controller_action_to_blacklist(nil, action) end @doc """ Removes controller action from the blacklist This function will update the blacklist of controller actions, following the same conventions as the blacklist described in the application configuration. The `controller` should be the qualified name of the Phoenix controller's Elixir module (e.g., `TimberClientAPI.OrganizationController`). The `action` should be the name of the action (e.g., `:index`). """ @spec remove_controller_action_from_blacklist(controller, action) :: :ok def remove_controller_action_from_blacklist(controller, action) do controller_action = {controller, action} blacklist = get_parsed_blacklist() new_blacklist = MapSet.delete(blacklist, controller_action) put_parsed_blacklist(new_blacklist) end @doc """ Removes a blacklisted controller from the blacklist This function will update the blacklist of controller actions, following the same conventions as the blacklist described in the application configuration. The `controller` should be the qualified name of the Phoenix controller's Elixir module (e.g., `TimberClientAPI.OrganizationController`). """ @spec remove_controller_from_blacklist(controller) :: :ok def remove_controller_from_blacklist(controller) do remove_controller_action_from_blacklist(controller, nil) end @doc """ Removes a blacklisted action from the blacklist This function will update the blacklist of controller actions, following the same conventions as the blacklist described in the application configuration. The `action` should be the name of the action (e.g., `:index`). """ @spec remove_action_from_blacklist(action) :: :ok def remove_action_from_blacklist(action) do remove_controller_action_from_blacklist(nil, action) end @doc false @spec controller_action_blacklisted?({controller, action}, parsed_blacklist) :: boolean def controller_action_blacklisted?({controller, action}, blacklist) do MapSet.member?(blacklist, {controller, action}) || MapSet.member?(blacklist, {controller, nil}) || MapSet.member?(blacklist, {nil, action}) end @doc false @spec get_parsed_blacklist() :: parsed_blacklist # The parsed version of the controller actions blacklist is stored in the # application environment at # [:timber_phoenix, :parsed_controller_actions_blacklist]. # This function fetches that value, returning an empty MapSet if the environment # entry does not exist def get_parsed_blacklist() do Application.get_env(:timber_phoenix, :parsed_controller_actions_blacklist, MapSet.new()) end @doc false @spec put_parsed_blacklist(parsed_blacklist) :: :ok def put_parsed_blacklist(parsed_blacklist) do Application.put_env(:timber_phoenix, :parsed_controller_actions_blacklist, parsed_blacklist) end # # Channels # @doc false @spec phoenix_channel_join(:start, compile_metadata :: map, runtime_metadata :: map) :: :ok @spec phoenix_channel_join( :stop, time_diff_native :: non_neg_integer, result_of_before_callback :: :ok ) :: :ok def phoenix_channel_join(:start, _compile, %{socket: socket, params: params}) do # Any value using to_string handles nil values since they are not always present. log_level = get_log_level() channel = to_string(socket.channel) topic = to_string(socket.topic) transport = to_string(socket.transport) serializer = to_string(socket.serializer) protocol_version = if Map.has_key?(socket, :vsn), do: socket.vsn, else: nil filtered_params = filter_params(params) params_json = JSON.try_encode_to_binary(filtered_params) event = %{ channel_joined: %{ channel: channel, params_json: params_json, protocol_version: protocol_version, serializer: serializer, topic: topic, transport: transport } } message = ["Joined channel ", channel, " with \"", topic, "\""] Logger.log(log_level, message, event: event) end def phoenix_channel_join(:stop, _compile, :ok), do: :ok def phoenix_channel_receive(:start, _compile, meta) do %{socket: socket, params: params, event: event_name} = meta log_level = get_log_level() channel = to_string(socket.channel) event_name = to_string(event_name) topic = to_string(socket.topic) transport = to_string(socket.transport) filtered_params = filter_params(params) params_json = JSON.try_encode_to_binary(filtered_params) event = %{ channel_event_received: %{ channel: channel, name: event_name, params_json: params_json, topic: topic, transport: transport } } message = ["Received ", event_name, " on \"", topic, "\" to ", channel] Logger.log(log_level, message, event: event) end def phoenix_channel_receive(:stop, _compile, :ok), do: :ok # # Controllers # @doc false @spec phoenix_controller_call(:start, compile_metadata :: map, runtime_metadata :: map) :: :ok @spec phoenix_controller_call( :stop, time_diff_native :: non_neg_integer, result_of_before_callback :: :ok ) :: :ok def phoenix_controller_call(:start, _, %{conn: conn}) do controller_actions_blacklist = get_parsed_blacklist() controller = Phoenix.Controller.controller_module(conn) action = Phoenix.Controller.action_name(conn) if !controller_action_blacklisted?({controller, action}, controller_actions_blacklist) do "Elixir." <> controller_name = to_string(controller) action_name = to_string(action) log_level = get_log_level() pipelines = inspect(conn.private[:phoenix_pipelines]) filtered_params = filter_params(conn.params) params_json = JSON.try_encode_to_binary(filtered_params) event = %{ controller_called: %{ action: action_name, controller: controller_name, params_json: params_json, pipelines: pipelines } } message = [ "Processing with ", controller_name, ?., action_name, ?/, ?2, " Pipelines: ", pipelines ] Logger.log(log_level, message, event: event) end :ok end def phoenix_controller_call(:stop, _time_diff, :ok) do :ok end @doc false @spec phoenix_controller_render(:start, map, map) :: :ok @spec phoenix_controller_render(:stop, non_neg_integer, :ok | {:ok, atom, String.t()} | false) :: :ok def phoenix_controller_render(:start, _compile_metadata, %{template: template_name, conn: conn}) do has_controller? = Map.has_key?(conn.private, :phoenix_controller) has_action? = Map.has_key?(conn.private, :phoenix_action) if has_controller? and has_action? do render_check(conn, template_name) else handle_render_blacklist(false, template_name) end end def phoenix_controller_render(:start, _compile_metadata, %{template: template_name}) do handle_render_blacklist(false, template_name) end def phoenix_controller_render(:start, _, _) do # Absolute fall-through. This catch-all is provided for any scenario that # has not been otherwise accounted for. It sets the return to :ok which will # result in no log being produced :ok end def phoenix_controller_render(:stop, _time_diff, :ok) do # The default return for phoenix_controller_render(:start, _, _) is :ok # If the parameters passed are [:stop, _, :ok], it means that the :start # phase failed and Phoenix is giving us :ok as the default # # In this case, we do nothing :ok end def phoenix_controller_render(:stop, _time_diff, false) do # The render event should not be logged :ok end def phoenix_controller_render(:stop, time_diff, {:ok, log_level, template_name}) do # This comes in as native time but is expected to be a float representing # milliseconds duration_ms = time_diff |> System.convert_time_unit(:native, :millisecond) |> :erlang.float() event = %{ template_rendered: %{ name: template_name, duration_ms: duration_ms } } message = ["Rendered ", ?", template_name, ?", " in ", Float.to_string(duration_ms), "ms"] Logger.log(log_level, message, event: event) :ok end # # Utility # # Takes a conn from a render event that definitely has a controller and action # and returns an appropriate response for the phoenix_controller_render :start event defp render_check(conn, template_name) do controller_actions_blacklist = get_parsed_blacklist() controller = Phoenix.Controller.controller_module(conn) action = Phoenix.Controller.action_name(conn) blacklisted? = controller_action_blacklisted?({controller, action}, controller_actions_blacklist) handle_render_blacklist(blacklisted?, template_name) end # Takes a boolean value that determines whether the render call is blacklisted # and returns an appropirate response for the phoenix_controller_render :start event defp handle_render_blacklist(true, _) do false end defp handle_render_blacklist(false, template_name) do log_level = get_log_level() {:ok, log_level, template_name} end defp filter_params(%Plug.Conn.Unfetched{}) do %{} end defp filter_params(params) when is_map(params) do params |> filter_values() |> Enum.into(%{}) end defp filter_params(params) when is_list(params) do filtered_params = filter_values(params) # In practice, it's actually improbable that the payload # will be a Keyword list, but we handle this as a safeguard if Keyword.keyword?(filtered_params) do Enum.into(filtered_params, %{}) else filtered_params end end # Non-structured type, take as-is defp filter_params(params) do filter_values(params) end defp filter_values(params) do if function_exported?(Phoenix.Logger, :filter_values, 1) do Phoenix.Logger.filter_values(params) else params end end end