Two approaches to Logging when Unit Testing with Python











up vote
1
down vote

favorite












Python allows logging to be used in several ways. What are the relative merits of these two approaches to Logging when Unit Testing with Python? Is one approach superior or does each approach suit 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









share|improve this question




















  • 2




    It's not clear what you are testing. Is your goal to test if correct output appears in the log?
    – Janne Karila
    Nov 23 at 7:02






  • 1




    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.
    – Martin Spamer
    2 days ago

















up vote
1
down vote

favorite












Python allows logging to be used in several ways. What are the relative merits of these two approaches to Logging when Unit Testing with Python? Is one approach superior or does each approach suit 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









share|improve this question




















  • 2




    It's not clear what you are testing. Is your goal to test if correct output appears in the log?
    – Janne Karila
    Nov 23 at 7:02






  • 1




    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.
    – Martin Spamer
    2 days ago















up vote
1
down vote

favorite









up vote
1
down vote

favorite











Python allows logging to be used in several ways. What are the relative merits of these two approaches to Logging when Unit Testing with Python? Is one approach superior or does each approach suit 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









share|improve this question















Python allows logging to be used in several ways. What are the relative merits of these two approaches to Logging when Unit Testing with Python? Is one approach superior or does each approach suit 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






python unit-testing logging






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited yesterday

























asked Nov 22 at 21:32









Martin Spamer

330212




330212








  • 2




    It's not clear what you are testing. Is your goal to test if correct output appears in the log?
    – Janne Karila
    Nov 23 at 7:02






  • 1




    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.
    – Martin Spamer
    2 days ago
















  • 2




    It's not clear what you are testing. Is your goal to test if correct output appears in the log?
    – Janne Karila
    Nov 23 at 7:02






  • 1




    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.
    – Martin Spamer
    2 days ago










2




2




It's not clear what you are testing. Is your goal to test if correct output appears in the log?
– Janne Karila
Nov 23 at 7:02




It's not clear what you are testing. Is your goal to test if correct output appears in the log?
– Janne Karila
Nov 23 at 7:02




1




1




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.
– Martin Spamer
2 days ago






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.
– Martin Spamer
2 days ago












1 Answer
1






active

oldest

votes

















up vote
1
down vote



accepted










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





share|improve this answer























    Your Answer





    StackExchange.ifUsing("editor", function () {
    return StackExchange.using("mathjaxEditing", function () {
    StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix) {
    StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
    });
    });
    }, "mathjax-editing");

    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "196"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    convertImagesToLinks: false,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: null,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














     

    draft saved


    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f208251%2ftwo-approaches-to-logging-when-unit-testing-with-python%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes








    up vote
    1
    down vote



    accepted










    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





    share|improve this answer



























      up vote
      1
      down vote



      accepted










      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





      share|improve this answer

























        up vote
        1
        down vote



        accepted







        up vote
        1
        down vote



        accepted






        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





        share|improve this answer














        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






        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited 2 days ago

























        answered Nov 23 at 0:42









        Neves4

        428




        428






























             

            draft saved


            draft discarded



















































             


            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f208251%2ftwo-approaches-to-logging-when-unit-testing-with-python%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Morgemoulin

            Scott Moir

            Souastre