Sub topic 4
Named loggers with getLogger
This chapter assumes you know basic Python modules and functions, and that you have run basicConfig once (covered in the previous chapter). It explains how to create loggers, what names to give them, and the mistakes that come from skipping this step.
What getLogger returns
logging.getLogger(name) looks up a logger by name in a registry that lives inside the logging module. If a logger with that name exists, you get that object. If not, the module creates it, stores it, and returns it. You never call the Logger class directly.
import logging
a = logging.getLogger("myapp")
b = logging.getLogger("myapp")
print(a is b)
print(a.name)
root = logging.getLogger()
print(root.name)
print(root is logging.getLogger("root"))The output is True, myapp, root, True. The last line is True only on Python 3.9 and later. Calling getLogger() with no argument, or with None, returns the root logger.
Because the registry is process-wide, two modules that ask for "myapp" share one logger. Any level or handler set through one reference is visible through the other.
The standard pattern: one logger per module
Use __name__ as the logger name and create the logger at module level:
import logging
logger = logging.getLogger(__name__)__name__ is the module's import path, such as payments or myapp.db.pool. This gives you three things:
- Each log record shows which module produced it.
- Names mirror your package layout, which is what later lets you control whole subtrees with one setting (the hierarchy chapter covers this).
- You never type a name by hand, so you cannot misspell one.
Here is a small two-file program. First payments.py:
import logging
logger = logging.getLogger(__name__)
def charge(amount):
logger.info("Charging %.2f", amount)
if amount <= 0:
logger.warning("Ignoring non-positive amount: %s", amount)
return False
return TrueThen main.py in the same directory:
import logging
import payments
logging.basicConfig(
level=logging.INFO,
format="%(name)s %(levelname)s %(message)s",
)
logger = logging.getLogger(__name__)
logger.info("Starting")
payments.charge(10)
payments.charge(-5)Running python main.py prints:
__main__ INFO Starting
payments INFO Charging 10.00
payments INFO Charging -5.00
payments WARNING Ignoring non-positive amount: -5Notice that payments.py never configures anything. It only creates a logger and emits records. The script that owns the program decides where the output goes. That split is the foundation of the library guidance later in this tutorial.
When a file runs as a script, __name__ is "__main__". That is why the first line shows __main__. This is normal, but if you want a stable name in a script's logs, you can pass a literal string instead.
What the module-level functions do
logging.info(...), logging.warning(...) and the other module-level functions send records through the root logger. They have a side effect that surprises people: if the root logger has no handlers, they call basicConfig() for you.
import logging
logging.info("This is a root logger call")
logging.basicConfig(level=logging.INFO)
logging.info("Second call")Only the first call to logging.info triggers the implicit setup, and it happens at the default WARNING level, so nothing is printed for it. The later basicConfig call then does nothing, because basicConfig returns silently when the root logger already has handlers. The second message is also dropped, because the root level is still WARNING. Pass force=True to basicConfig (Python 3.8+) if you really need to reconfigure.
Root logger calls also lose the module name, since every record is named root. Named loggers avoid that.
What happens with no configuration
If you create a logger and never configure logging at all, Python still prints warnings and errors, but nothing else:
import logging
log = logging.getLogger("demo")
log.info("hidden")
log.warning("shown")Only shown appears, on stderr, with no timestamp or level. This comes from a fallback handler called logging.lastResort. It is used only when no handler is found anywhere in the logger's chain, and its level is WARNING. The logger demo has no level of its own, so it uses the root's default, WARNING, which is why hidden never gets that far.
This explains a common confusion: "my logger.info calls print nothing." The logger exists, but nothing has lowered the threshold or attached a handler for INFO.
Setting a level on a logger
A logger can have its own level, which filters records at the moment you call logger.info(...) or a similar method. A level of NOTSET (the default for new loggers) means "ask my parent." The hierarchy chapter explains inheritance in detail. For now, remember:
import logging
logging.basicConfig(level=logging.DEBUG)
noisy = logging.getLogger("noisy.lib")
noisy.setLevel(logging.ERROR)
noisy.warning("dropped")
logging.getLogger("mine").debug("shown")Setting a level on one logger affects only that logger (and, as you will see, its descendants). It does not touch other loggers or the handlers.
Child names with getChild
When you want a sub-logger for part of a module, getChild appends a suffix with a dot:
import logging
logger = logging.getLogger("myapp")
db_logger = logger.getChild("db")
print(db_logger.name)
print(db_logger is logging.getLogger("myapp.db"))Both lines print their expected values: myapp.db and True. getChild is handy inside a library where __name__ is already the base name.
Loggers inside classes and functions
Create loggers once and reuse them. Calling getLogger is cheap because it is a dictionary lookup with a lock, but there is no benefit to doing it on every call. These forms all work:
import logging
logger = logging.getLogger(__name__)
class Worker:
def __init__(self, name):
self.log = logging.getLogger(f"{__name__}.{type(self).__name__}")
self.name = name
def run(self):
self.log.info("Worker %s running", self.name)
logger.debug("Module-level logger still available")The module-level logger is the right default. Class-specific names are fine when the set of names is small and fixed.
Common errors
| Mistake | Effect | Fix |
|---|---|---|
| `logging.getLogger(__file__)` | Names contain slashes and dots from a path, breaking the hierarchy. | Use `__name__`. |
| Typing a name by hand in each file | Typos create two unrelated loggers. | Use `__name__`. |
| Using `logging.info` in library code | Output goes to the root logger and may trigger implicit `basicConfig`. | Use a module-level named logger. |
| Calling `basicConfig` in a library module | Overrides decisions that belong to the application. | Configure only in the entry point. |
| Building the message with an f-string | The string is built even when the level would drop it. | Pass arguments: `logger.debug("n=%d", n)`. |
| Expecting `getLogger("a.b")` to need `getLogger("a")` first | Not required, but intermediate names still count in the hierarchy. | Create loggers freely. Names alone define relationships. |
The lazy-argument form deserves a short explanation. With logger.debug("Loaded %d rows from %s", n, path), the logging machinery builds the final string only if the record passes the level check and reaches a handler. An f-string pays that cost every time, and it also evaluates its expressions even if the message will be discarded.
Exercise
A file billing/invoices.py contains logger = logging.getLogger(__name__). The application is started with python -m billing.invoices and with basicConfig(format="%(name)s %(message)s"). What names appear in records when the file is run as a script, and what names appear when another module does import billing.invoices?
Show answer
When run with python -m billing.invoices, the module's __name__ is "__main__", so records show __main__. When imported by another module, __name__ is "billing.invoices", so records show billing.invoices. The same source file therefore produces different logger names depending on how it is started.
Exercise
You write logging.info("start") as the first line of a script, then call logging.basicConfig(level=logging.INFO) and logging.info("ready"). Which messages are printed, and why?
Show answer
Neither is printed. The first logging.info call sees no root handlers and calls basicConfig() with defaults (WARNING level). The later basicConfig call is then ignored because the root logger already has a handler, so the root level stays at WARNING and the INFO messages are dropped. Move basicConfig before the first logging call, or pass force=True.