How do I still print logs to console while running ExUnit tests?
Asked Answered
E

2

8

For debugging purposes during a failing integration test, I would like to still be able to see my application logs. Is there a command I can pass to the mix test task to accomplish this?

Eiderdown answered 26/7, 2016 at 0:19 Comment(0)
U
8

Every mix project has a config.exs file. When mix starts, it loads this file. A common pattern in elixir is to define configs for different environments, like test.exs, dev.exs, prod.exs, etc, etc.

Many projects like Phoenix will generate these files for you in your config folder, and you'll see this line in your config.exs line:

import_config "#{Mix.env}.exs"

When you run mix test it sets MIX_ENV environment variable to "test" which means the import_config line loads your test.exs file.

So in order to set your logging level for just your tests, in your test.exs file you can write the following:

# Print only warnings and errors during test
config :logger, level: :warn
Updraft answered 26/7, 2016 at 0:33 Comment(1)
This answer explains nicely where to edit test config, but not how to edit it to show debug logs. See my answer for configuration that will enable logs in test.Unwashed
U
0

In order to show IO.inspects and other debug logs on mix test, change the following config:

  1. In config/test.exs, find the following line:
# Print only warnings and errors during test
config :logger, level: :warn
  1. Comment the previous line out and add the following config with the compile_time_purge_matching option:
config :logger,
  backends: [:console],
  compile_time_purge_matching: [
    [level_lower_than: :debug]
  ]

When you are finished debugging your tests, comment out the compile_time_purge_matching config in step 2 and uncomment your original level: :warn config to avoid messy test logs.

Older Versions Note: If you are on an older version of Elixir, use the following deprecated config in place of compile_time_purge_matching:

config :logger,
  backends: [:console],
  compile_time_purge_level: :debug

compile_time_purge_level: debug will still work on Elixir 1.12 with deprecation warnings.

Unwashed answered 17/6, 2021 at 1:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.