Luan Pham
Luan Pham

Reputation: 599

Python: What are differences between `logger.info` and `logging.info`?

I wonder what is the differences between two versions below? And how to use it effectively?

Version 1:

import logging
logging.info("Hello world!")

Version 2:

import logging
logger = logging.getLogger(__name__)
logger.info("Hello world!")

Upvotes: 4

Views: 3259

Answers (2)

Albert Nguyen
Albert Nguyen

Reputation: 377

I run my code:

class TestBedLog():
    async def test(self):

        import logging

        logging.info("Log from logging")

        logger = logging.getLogger(__name__)
        logger.info("Log from logger")

And the result is:

root: INFO: Log from logging
src.myserver.test.test_apiv2.test_bedlog: INFO: Log from logger

As you can see, logging is from the root. And logger you will see the file where log the information

Upvotes: 2

deceze
deceze

Reputation: 522382

The advantage of using a logging.getLogger(__name__) (or any more custom name) is that logs will show up with the logger's name, in this case the module's name, in your logs, easily letting you distinguish which module caused which message. Further you are able to selectively configure a specific module's logs somewhere in a central configuration file, like:

logging.getLogger('that.module.name').setLevel(logging.INFO)

For example, if you're setting your general logging level to DEBUG, but there's one very noisy module somewhere which causes a ton of superfluous output, you could suppress that selectively.

Upvotes: 1

Related Questions