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!")
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.
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
logging.info
is the same as callinggetLogger()
without argument and using the root logger. see docs.python.org/3/howto/logging.html – blues