Skip to content

Commit

Permalink
Compute ANSI escaping lazily in Logger, closes #14248
Browse files Browse the repository at this point in the history
  • Loading branch information
josevalim committed Feb 1, 2025
1 parent 07afa71 commit cff55fb
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 9 deletions.
15 changes: 8 additions & 7 deletions lib/logger/lib/logger/formatter.ex
Original file line number Diff line number Diff line change
Expand Up @@ -175,8 +175,7 @@ defmodule Logger.Formatter do
warning: Keyword.get(colors, :warning, :yellow),
notice: Keyword.get(colors, :info, :normal),
info: Keyword.get(colors, :info, :normal),
debug: Keyword.get(colors, :debug, :cyan),
enabled: Keyword.get(colors, :enabled, IO.ANSI.enabled?())
debug: Keyword.get(colors, :debug, :cyan)
}
end

Expand Down Expand Up @@ -222,11 +221,13 @@ defmodule Logger.Formatter do

defp format_fa(fun, arity), do: [Atom.to_string(fun), "/", Integer.to_string(arity)]

defp colorize(data, _level, %{enabled: false}, _md), do: data

defp colorize(data, level, %{enabled: true} = colors, md) do
color = md[:ansi_color] || Map.fetch!(colors, level)
[IO.ANSI.format_fragment(color, true), data | IO.ANSI.reset()]
defp colorize(data, level, colors, md) do
if Map.get_lazy(colors, :enabled, &IO.ANSI.enabled?/0) do
color = md[:ansi_color] || Map.fetch!(colors, level)
[IO.ANSI.format_fragment(color, true), data | IO.ANSI.reset()]
else
data
end
end

@doc """
Expand Down
4 changes: 2 additions & 2 deletions lib/logger/test/logger/formatter_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ defmodule Logger.FormatterTest do
)

assert %{
level: :warn,
level: :warning,
msg: {:string, "foo"},
meta: %{
mfa: {Logger.Formatter, :compile, 1}
Expand All @@ -83,7 +83,7 @@ defmodule Logger.FormatterTest do
)

assert %{
level: :warn,
level: :warning,
msg: {:string, "message"},
meta: %{
mfa: {Logger.Formatter, :compile, 1},
Expand Down

0 comments on commit cff55fb

Please sign in to comment.