Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

allow users to filter out certain handle_in messages #5943

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions lib/phoenix/channel.ex
Original file line number Diff line number Diff line change
Expand Up @@ -332,6 +332,20 @@ defmodule Phoenix.Channel do
Note that changing an event type's level doesn't affect what is logged,
unless you set it to `false`, it affects the associated level.
To filter out logs for certain messages, you can pass a function to the
`:log_join` and `:log_handle_in` options. The function should return `false`
for messages you want to filter out, and `:debug` or `:info` for messages
you want to log.
For example, to filter out handle_in messages when the event name starts
with "ping_" and matches `%{"pong" => true}` in params:
use Phoenix.Channel, log_handle_in: &__MODULE__.filter_ping/2
def filter_ping("ping_" <> _, %{"pong" => true}), do: false
def filter_ping(_, _), do: :debug
"""
alias Phoenix.Socket
alias Phoenix.Channel.Server
Expand Down
21 changes: 16 additions & 5 deletions lib/phoenix/logger.ex
Original file line number Diff line number Diff line change
Expand Up @@ -343,7 +343,7 @@ defmodule Phoenix.Logger do

@doc false
def phoenix_channel_joined(_, %{duration: duration}, %{socket: socket} = metadata, _) do
channel_log(:log_join, socket, fn ->
channel_log(:log_join, metadata, fn ->
%{result: result, params: params} = metadata

[
Expand All @@ -364,7 +364,7 @@ defmodule Phoenix.Logger do

@doc false
def phoenix_channel_handled_in(_, %{duration: duration}, %{socket: socket} = metadata, _) do
channel_log(:log_handle_in, socket, fn ->
channel_log(:log_handle_in, metadata, fn ->
%{event: event, params: params} = metadata

[
Expand All @@ -382,10 +382,21 @@ defmodule Phoenix.Logger do
end)
end

defp channel_log(_log_option, %{topic: "phoenix" <> _}, _fun), do: :ok
defp channel_log(_log_option, %{socket: %{topic: "phoenix" <> _}}, _fun), do: :ok

defp channel_log(log_option, %{private: private}, fun) do
if level = Map.get(private, log_option) do
defp channel_log(log_option, %{socket: %{private: private}, event: event, params: params}, fun) do
log_option = Map.get(private, log_option)

level =
cond do
is_function(log_option, 2) ->
log_option.(event, params)

true ->
log_option
end

if level do
Logger.log(level, fun)
end
end
Expand Down