【问题标题】:How do I still print logs to console while running ExUnit tests?如何在运行 ExUnit 测试时仍将日志打印到控制台?
【发布时间】:2021-06-17 09:37:11
【问题描述】:

为了在失败的集成测试期间进行调试,我希望仍然能够看到我的应用程序日志。有没有我可以传递给mix test 任务的命令来完成这个任务?

【问题讨论】:

    标签: elixir ex-unit


    【解决方案1】:

    每个混音项目都有一个config.exs 文件。当 mix 开始时,它会加载这个文件。 Elixir 中的一个常见模式是为不同的环境定义配置,例如test.exsdev.exsprod.exs 等。

    像 Phoenix 这样的许多项目会在您的 config 文件夹中为您生成这些文件,您会在您的 config.exs 行中看到这一行:

    import_config "#{Mix.env}.exs"
    

    当您运行 mix test 时,它会将 MIX_ENV 环境变量设置为“test”,这意味着 import_config 行会加载您的 test.exs 文件。

    因此,为了为您的测试设置日志级别,您可以在 test.exs 文件中编写以下内容:

    # Print only warnings and errors during test
    config :logger, level: :warn
    

    【讨论】:

    • 这个答案很好地解释了在哪里编辑测试配置,但没有解释如何编辑它以显示调试日志。请参阅我的答案,了解将启用测试日志的配置。
    【解决方案2】:

    为了在mix test 上显示IO.inspects 和其他调试日志,请更改以下配置:

    1. config/test.exs 中,找到以下行:
    # Print only warnings and errors during test
    config :logger, level: :warn
    
    1. 注释掉上一行并使用compile_time_purge_matching 选项添加以下配置:
    config :logger,
      backends: [:console],
      compile_time_purge_matching: [
        [level_lower_than: :debug]
      ]
    

    完成调试测试后,注释掉 compile_time_purge_matching 在步骤 2 中配置并取消注释 你原来的 level: :warn 配置以避免混乱的测试日志。

    旧版本注意:如果您使用的是旧版本的 Elixir, 使用以下已弃用的配置代替 compile_time_purge_matching

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

    compile_time_purge_level: debug 仍可在 Elixir 1.12 上运行,但会出现弃用警告。

    【讨论】:

      猜你喜欢
      • 2016-07-25
      • 1970-01-01
      • 2010-10-22
      • 1970-01-01
      • 2015-10-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多