1
\$\begingroup\$

Python allows logging to be used in several ways. Can you review the relative merits of these two approaches to Logging when Unit Testing with Python? Is one approach appropriate to specific circumstances? What are those circumstances and how might each approach be improved?

Directly addressing the logger.

#!/usr/bin/env python
import logging
import unittest

class LoggingTest(unittest.TestCase):

    logging.basicConfig(level=logging.INFO)

    def test_logger(self):
        logging.info("logging.info test_logger")
        pass

Getting a logger by name

#!/usr/bin/env python
import logging
import unittest

class GetLoggerTest(unittest.TestCase):
    logger = logging.getLogger(__name__)
    logger.setLevel(logging.INFO)

    def test_logger(self):
        self.logger.info("self.logger.info test_logger")
        pass
\$\endgroup\$
  • 2
    \$\begingroup\$ It's not clear what you are testing. Is your goal to test if correct output appears in the log? \$\endgroup\$ – Janne Karila Nov 23 '18 at 7:02
  • 1
    \$\begingroup\$ This comment seems immaterial to the code to be reviewed. I am asking for a review of the two different approaches to logging shown. This review is about the logging not testing. \$\endgroup\$ – Martin Spamer Nov 23 '18 at 18:46
1
\$\begingroup\$

According to the logging docs:

The logger name hierarchy is analogous to the Python package hierarchy, and identical to it if you organise your loggers on a per-module basis using the recommended construction logging.getLogger(__name__). That’s because in a module, __name__ is the module’s name in the Python package namespace.

Based on my experience, I would say that you should always use logging.getLogger(__name__) for bigger projects, as it'll make logging modularization easier.

As your question is broad, I recommend you to read the Logging Cookbook, in this link, as it holds many important use cases in which you could optimize the way you use logging.

It's also possible to mix both cases in order to add a timestamp, in example, which is an improved way of using this module:

#!/usr/bin/env python
import logging
import unittest

class GetLoggerTest(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.INFO)

    def test_logger(self):
        self.logger.info("self.logger.info test_logger")
        pass
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.