Skip to content

Commit

Permalink
allows user to filter out certain handle_in messages
Browse files Browse the repository at this point in the history
Signed-off-by: Cocoa <[email protected]>
  • Loading branch information
cocoa-xu committed Oct 3, 2024
1 parent d00f197 commit facaabc
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 5 deletions.
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

0 comments on commit facaabc

Please sign in to comment.