我想知道在测试时如何禁用Elixir中的日志记录。在我当前的代码中,我测试记录器消息,所以我不想完全禁用它,而是在任何测试停止通过之前隐藏消息。
我正在使用mix和ExUnit来管理和测试我的项目。
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发布于 2018-09-06 18:23:06
要么使用ExUnit.CaptureLog
import ExUnit.CaptureLog
test "example" do
assert capture_log(fn ->
Logger.error "log msg"
end) =~ "log msg"
end或者,如果您只想忽略任何日志,那么:
@tag capture_log: true
test "example" do
Logger.error "log msg"
end发布于 2017-12-28 01:14:18
将以下记录器配置放入config/test.exs文件中:
config :logger, level: :error如果您没有特定于环境的配置,请在config/config.exs中放入以下行
config :logger, level:
case Mix.env do
:test -> :error
_ -> :info
end另一种选择是为日志消息使用另一个后端(假设{:logger_file_backend, "~> 0.0"}包含在mix.exs的deps部分中):
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发布于 2017-12-28 02:17:26
我在记录器的文档中发现了remove_backend()函数,所以在应该禁用记录器的文件中使用Logger.remove_backend(:console)之后,所有记录的消息都消失了(顺便说一句,测试正在通过)。
编辑:我向Logger提出了这个问题。显然,在测试之上使用@moduletag :capture_log要比移除后端更好。无论如何,工作,所以对我来说很好。
https://stackoverflow.com/questions/47996005
复制相似问题