Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Suppress Logger when testing

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
like image 262
Jump3r Avatar asked Dec 27 '17 17:12

Jump3r


People also ask

How do I test a logger message in Junit?

@StefanoL: If a logger is defined with private static final Logger LOGGER = Logger. getLogger(someString); , you can still access it from unit tests with Logger. getLogger(someString); , modify it and add handlers (as in the accepted answer).

How do I enable logging in Django?

By default, the LOGGING setting is merged with Django's default logging configuration using the following scheme. If the disable_existing_loggers key in the LOGGING dictConfig is set to True (which is the dictConfig default if the key is missing) then all loggers from the default configuration will be disabled.


2 Answers

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
like image 78
Kelu Thatsall Avatar answered Oct 06 '22 08:10

Kelu Thatsall


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
like image 44
Aleksei Matiushkin Avatar answered Oct 06 '22 08:10

Aleksei Matiushkin