0

Background

I have library that logs messages depending on the value of disable_logging:

unless Application.get(:my_app, :disable_logging, false), do:
  Logger.info("Hello World!")

Depending on MIX_ENV I have a config for each setup:

#test.config
use Mix.Config
config :my_app, disable_logging: true

Problem

The issue here is that I don't want log messages all over my test results. So, naturally, I could set the disable_logging to true and be done with it.

However, if I do it, I can't test whether or not the Logger is being called and if it's being called with the correct values:

Question

So, given this I have some questions:

  1. Is there a way to activate logs but without outputting them to the terminal when I am running tests?
  2. Is there a way to only activate logs for some tests in my test suite?

2 Answers 2

1

Declare ExUnit.setup/1 with a mandatory ExUnit.on_exit/2 to set the environment variable with Application.put_env/4.

setup do
  Application.put_env(:my_app, :disable_logging, false)

  on_exit fn ->
    Application.put_env(:my_app, :disable_logging, true)
  end

  :ok
end

I did not test it, but it should work.

1
  • Yes. SO rules explicitly state 1 question per post, so I answered the last one. For the first, use whatever file logger backend and configure your test suits to use it. This behaviour is common across all the environments, it is not tests-specific and has basically nothing in common with the text above. Commented Jan 15, 2019 at 15:23
1

Why not keep using ExUnit.CaptureLog to suppress the logs and just discard the result?


If you have a large number of tests that log to console and don't want to do that for all of them, you can create a custom ExUnit tag, combined with @Aleksei's answer, that does it for you.

In your ExUnit.Case template, add this:

setup tags do
  if tags[:disable_logger] do
    Application.put_env(:my_app, :disable_logging, false)

    on_exit(fn ->
      Application.put_env(:my_app, :disable_logging, true)
    end)
  end

  :ok
end

Now you can just specify the tag for the tests you want logging disabled for:

@tag disable_logger: true
test "something happens" do
  # ...
end

Note: You will encounter issues with this if you run your tests asynchronously

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.