Skip to content

Commit a8b2cb9

Browse files
author
José Valim
committed
Use to_string when possible on Logger.log
1 parent 6827431 commit a8b2cb9

File tree

2 files changed

+13
-1
lines changed

2 files changed

+13
-1
lines changed

lib/logger/lib/logger.ex

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -221,6 +221,7 @@ defmodule Logger do
221221
"""
222222

223223
@type backend :: GenEvent.handler
224+
@type message :: IO.chardata | String.Chars.t
224225
@type level :: :error | :info | :warn | :debug
225226
@levels [:error, :info, :warn, :debug]
226227

@@ -367,7 +368,7 @@ defmodule Logger do
367368
Use this function only when there is a need to log dynamically
368369
or you want to explicitly avoid embedding metadata.
369370
"""
370-
@spec log(level, IO.chardata | (() -> IO.chardata), Keyword.t) ::
371+
@spec log(level, message | (() -> message), Keyword.t) ::
371372
:ok | {:error, :noproc} | {:error, :timeout} | {:error, term}
372373
def log(level, chardata, metadata \\ []) when level in @levels and is_list(metadata) do
373374
%{mode: mode, truncate: truncate, timeout: timeout,
@@ -458,6 +459,8 @@ defmodule Logger do
458459
do: Logger.Utils.truncate(data.(), n)
459460
defp truncate(data, n) when is_list(data) or is_binary(data),
460461
do: Logger.Utils.truncate(data, n)
462+
defp truncate(data, n),
463+
do: Logger.Utils.truncate(to_string(data), n)
461464

462465
defp notify(:sync, msg, timeout), do: GenEvent.sync_notify(Logger, msg, timeout)
463466
defp notify(:async, msg, _timeout), do: GenEvent.notify(Logger, msg)

lib/logger/test/logger_test.exs

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -155,6 +155,15 @@ defmodule LoggerTest do
155155
Logger.configure(truncate: 8096)
156156
end
157157

158+
test "log/2 with to_string/1 conversion" do
159+
Logger.configure(truncate: 4)
160+
assert capture_log(fn ->
161+
Logger.log(:debug, :hello)
162+
end) =~ "hell (truncated)"
163+
after
164+
Logger.configure(truncate: 8096)
165+
end
166+
158167
test "log/2 does not fails when the Logger is off" do
159168
logger = Process.whereis(Logger)
160169
Process.unregister(Logger)

0 commit comments

Comments
 (0)