Suppress Logger when testing

testing logging elixir

2442 观看


507 作者的声誉

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
作者: Jump3r 的来源 发布者: 2017 年 12 月 27 日

回应 (3)


92569 作者的声誉

Into your config/test.exs file put the following config for the logger:

If you don’t have environment-specific configs, put the following line in your config/config.exs:

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):

作者: Aleksei Matiushkin 发布者: 27.12.2017 05:14


507 作者的声誉

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.

作者: Jump3r 发布者: 27.12.2017 06:17


1562 作者的声誉

Either use ExUnit.CaptureLog:

import ExUnit.CaptureLog

test "example" do
   assert capture_log(fn ->
      Logger.error "log msg"
   end) =~ "log msg"

Or if you just want to ignore any logs then:

@tag capture_log: true
test "example" do
    Logger.error "log msg"
作者: Kelu Thatsall 发布者: 06.09.2018 10:23