Reputation: 1028
I wonder how to disable logging in Elixir when testing. In my current code I test for logger messages, so I don't want to disable it completely, but hide the messages until any test stop passing.
I'm using mix and ExUnit to manage and test my project.
mix test
Compiling 2 files (.ex)
.........
17:59:18.446 [warn] Code seems to be empty
.
17:59:18.447 [warn] Code doesn't contain HLT opcode
.
17:59:18.448 [warn] Code doesn't contain HLT opcode
17:59:18.448 [error] Label error doesn't exist
.....
Finished in 0.07 seconds
16 tests, 0 failures
Upvotes: 18
Views: 8292
Reputation: 2541
Either use ExUnit.CaptureLog
:
import ExUnit.CaptureLog
test "example" do
assert capture_log(fn ->
Logger.error "log msg"
end) =~ "log msg"
end
Or if you just want to ignore any logs then:
@tag capture_log: true
test "example" do
Logger.error "log msg"
end
Upvotes: 29
Reputation: 1028
I spotted remove_backend()
function in Logger's docs, so after using
Logger.remove_backend(:console)
in file where Logger should be disabled, every logged message is gone (tests are passing by the way).
EDIT: I asked Logger devs this question. Apparently, it's better to use @moduletag :capture_log
on top of the test than removing backend. Anyway, works, so fine for me.
Upvotes: 7
Reputation: 121000
Into your config/test.exs
file put the following config for the logger:
config :logger, level: :error
If you don’t have environment-specific configs, put the following line in your config/config.exs
:
config :logger, level:
case Mix.env do
:test -> :error
_ -> :info
end
Another option would be to use another backend for the logging messages (assuming {:logger_file_backend, "~> 0.0"}
is included in deps
section of mix.exs
):
config :logger,
compile_time_purge_level: :debug,
format: "$date $time $metadata[$level] $message\n",
metadata: [:application, :module, :function, :file, :line],
backends: [{LoggerFileBackend, :info_warn_error}]
config :logger, :info_warn_error,
path: "log/info_warn_error.log", # or "/dev/null"
level: :warn
Upvotes: 9