简体   繁体   中英

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:

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. 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) .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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