简体   繁体   English

如何在 Python 的单元测试中设置日志记录级别

[英]How to set logging level in a unit test for Python

I am running a particular unit test in my library, and I would like to get more logging from it.我正在我的库中运行一个特定的单元测试,我想从中获得更多的日志记录。 I am running it in the following way:我以以下方式运行它:

python -m unittest my_module.my_submodule_test.MyTestClass.test_my_testcase

Because I'm doing this, the my_submodule_test.py file does not run the bottom part where I set the log level like so:因为我正在这样做,所以my_submodule_test.py文件不会运行我设置日志级别的底部,如下所示:

if __name__ == '__main__':
  logging.getLogger().setLevel(logging.DEBUG)
  unittest.main()

How can I programatically set the log level so that I can get more detailed logging from my test?如何以编程方式设置日志级别,以便从测试中获得更详细的日志记录?

Also, I'd like to be able to set the logging via a command-line argument.另外,我希望能够通过命令行参数设置日志记录。 Is there a way to do that?有没有办法做到这一点?

One way in which this can be done is by doing it in the setUp code of your TestCase subclass.可以做到这一点的一种方法是在setUp子类的设置代码中TestCase You would do the following:您将执行以下操作:

class MyTestClass(unittest.TestCase):

  def setUp(self):
    logging.basicConfig(level=logging.DEBUG)
    logging.getLogger().setLevel(logging.DEBUG)

You can use either logging.basicConfig(level=logging.DEBUG) , or logging.getLogger().setLevel(logging.DEBUG) .您可以使用logging.basicConfig(level=logging.DEBUG)logging.getLogger().setLevel(logging.DEBUG)

This should activate logging for your whole project (unless you are changing the level for loggers further down in the hierarchy that you care about).这应该为您的整个项目激活日志记录(除非您在您关心的层次结构中更改记录器的级别)。

I do not know of a way to do this from the command line, unfortunately.不幸的是,我不知道从命令行执行此操作的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM