Sub topic 4
Named loggers with getLogger
This chapter assumes you know Python functions, modules, and classes, and that you have seen log levels and basicConfig. Here you will learn how to create named loggers and why every module should have one.
Why not log through the root logger
The functions logging.info() and logging.warning() write to the root logger. That works in a short script. In a larger program every message then carries the name root, so you cannot tell which module produced it. You also cannot change the level for one part of the program.
A named logger fixes both problems.
Creating a logger with getLogger
logging.getLogger(name) returns the logger with that name. If it does not exist yet, Python creates it. If it exists, you get the same object back.
import logging
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s %(levelname)s %(name)s: %(message)s",
)
a = logging.getLogger("myapp.billing")
b = logging.getLogger("myapp.billing")
print(a is b)
a.info("Invoice %d created", 42)The program prints True, because both calls return one object. The log line shows myapp.billing as the logger name, so you can see where it came from.
Because of this, you never need to pass a logger around. Any module can call getLogger with the same name and get the shared logger.
The `__name__` convention
The usual choice is one logger per module, named after the module:
import logging
logger = logging.getLogger(__name__)
def charge(amount):
logger.info("Charging %s", amount)
if amount <= 0:
logger.warning("Unusual amount: %s", amount)__name__ is the module's import name. In a file myapp/billing.py it is myapp.billing. The dots in the name matter: they define a parent and child relationship between loggers, which a later chapter covers. For now, remember that myapp.billing is a child of myapp.
When you run a file directly, __name__ is "__main__". Log lines from that file then show __main__ as the logger name. This is normal.
Passing arguments to log calls
Pass values as arguments instead of building the string yourself:
logger.info("User %s bought %d items", user, count)Python only formats the message if the record is actually emitted. With an f-string, the formatting work happens even when the level would discard the message. This matters for DEBUG calls in hot loops.
Common mistakes
- Passing a name that differs by case or spelling.
"MyApp"and"myapp"are two separate loggers. - Calling
logging.info()inside a module that has its own logger. The message goes to the root logger and loses its name. - Creating loggers inside functions with a new name each time. Loggers are never garbage collected, so generating unique names leaks memory.
- Expecting a logger to print by itself. A logger only creates records. Handlers decide where they go, which the next chapter covers.
Checking a logger's name
Each logger has a name attribute, and each record carries it as %(name)s:
import logging
logger = logging.getLogger("myapp.billing")
print(logger.name)
print(logger.parent.name)This prints myapp.billing, then root. The parent is root because no logger called myapp has been created yet. Python links the logger to the nearest existing ancestor.
Exercise
A module shop/cart.py runs logger = logging.getLogger(__name__) at the top. Another module, shop/checkout.py, runs getLogger("shop.cart"). Are these the same logger? What name appears in the output when shop/cart.py is imported, and what name appears when it is run directly with python shop/cart.py?
Show answer
Yes, they are the same object, because getLogger returns the existing logger for a given name. When imported as part of the shop package, __name__ is shop.cart. When run directly, __name__ is __main__, so the logger is named __main__ and is a different logger from shop.cart.