Search code examples
pythonunit-testinglogging

How to enable logging in python test cases?


I have a Python test case like this:

class TestUnitTest(unittest.TestCase):
    logger = logging.getLogger(__name__)
    logging.basicConfig(format = '%(asctime)s %(module)s %(levelname)s: %(message)s',
                    datefmt = '%m/%d/%Y %I:%M:%S %p', level = logging.DEBUG)


    def setUp(self):
        self.logger.debug("inside setup")

    def test_method1(self):
        self.logger.debug("inside test_method1")

        self.assertTrue(True)

But I don't see any log statement when I run the test.

I only see this in the output. Can you please tell me what I am missing?

Running tests...
----------------------------------------------------------------------
  test_method1(__main__.TestUnitTest) ... OK (0.000s)

----------------------------------------------------------------------
Ran 1 test in 0.000s

Solution

  • I would recommend using a slightly different setup: then it's very clear where logging is configured. In your example, something else could be configuring logging, causing your basicConfig() call to become a no-op. This script:

    # so_76732816.py
    import logging
    import unittest
    
    logger = logging.getLogger(__name__)
    
    class TestUnitTest(unittest.TestCase):
    
        def setUp(self):
            logger.debug("inside setup")
    
        def test_method1(self):
            logger.debug("inside test_method1")
            self.assertTrue(True)
    
    if __name__ == '__main__':
        logging.basicConfig(format = '%(asctime)s %(module)s %(levelname)s: %(message)s',
                        datefmt = '%m/%d/%Y %I:%M:%S %p', level = logging.DEBUG)
        unittest.main()
    

    prints, when run,

    07/22/2023 02:27:23 PM so_76732816 DEBUG: inside setup
    07/22/2023 02:27:23 PM so_76732816 DEBUG: inside test_method1
    .
    ----------------------------------------------------------------------
    Ran 1 test in 0.000s
    
    OK
    

    Note that you gain nothing from nesting the logger inside the test case. It's named after the module (__name__), so it might as well be at module level as in my example. Also, the basicConfig() is called from the __name__ == '__main__' clause, so it should run before anything else.