Address These 5 Questions to Understand Python Logging | by Yong Cui, Ph.D. | Better Programming | Nov, 2020

When we use the logging module, the first thing that we usually do is to instantiate the logger object. Technically, we can create a logger object by calling the Logger constructor:

import logginglogger_not_good = logging.Logger("my_app")

However, as indicated by the logger name above, it’s not a good practice to create the logger using the constructor. Instead, the best practice is to use the module-level function getLogger, which will retrieve the same logger object for a given app:

logger_good = logging.getLogger("my_app")

As shown below, multiple calls of the getLogger function retrieve the same object, as shown by its identical memory address. By contrast, using the construction method will create multiple instances:

Logger object

The logger object is the central object that controls the logging behavior of your app or module. Some important things that you should consider include logging levels, handlers, and formatting, which will be discussed in the next few sections.

Share:

More Posts

Send Us A Message