Python logging — Levels, Handlers, and Formatters
Print statements vanish when a program grows. The logging module in the standard library gives each message a level, a logger name, and a destination, and the program decides which levels reach which destination. This guide builds logging one piece at a time: a named logger with a handler and a formatter first, then the level numbers and filtering, the basicConfig shortcut, two handlers with two levels, child loggers in the name hierarchy, message arguments and exception records, and the traps a first logging setup usually meets. Each step is a small working program with the exact output it prints.
Written November 13, 2026 · Tested with Python 3.12.3 · 12 min read
- The main program: a logger, a handler, a formatter
- Levels: names, numbers, and the first filter
- basicConfig: the one-call shortcut
- Two handlers, two levels: the file keeps more than the screen
Written November 13, 2026
Tested with Python 3.12.3
What this guide is
A log record starts at a logger. The logger checks the record level against its own level, then passes the record to its handlers. Each handler writes the record to one destination, such as the screen or a file, and a formatter turns the record into the text line that lands there. Three choices shape the output: the logger level decides which records exist, the handler level decides which of those records a destination takes, and the formatter decides what each line looks like. The getLogger function returns a logger by name, and the same name always returns the same logger, so modules that ask for one name share one setup.
The main program: a logger, a handler, a formatter
The program below sets all three pieces by hand. The logger level is DEBUG, the lowest named level, so every message passes. The handler writes to standard output instead of the default standard error, and its formatter puts the level, the logger name, and the message on each line. The propagate flag is off, so the records do not also travel to the root logger and print twice:
import logging, sys
logger = logging.getLogger("shop")
logger.setLevel(logging.DEBUG)
handler = logging.StreamHandler(sys.stdout)
handler.setFormatter(logging.Formatter("%(levelname)s %(name)s: %(message)s"))
logger.addHandler(handler)
logger.propagate = False
logger.debug("cart opened")
logger.info("item added")
logger.warning("stock low")
logger.error("payment failed")
logger.critical("database down")
The exact output:
DEBUG shop: cart opened
INFO shop: item added
WARNING shop: stock low
ERROR shop: payment failed
CRITICAL shop: database down
Each of the five calls names a level, and the method name is the level in lowercase. The formatter fields in parentheses come from the record: levelname is the level text, name is the logger name passed to getLogger, and message is the text the call supplied. A handler with no formatter prints the message alone, with no level or name, so the formatter is where the context on every line comes from.
Levels: names, numbers, and the first filter
The five named levels are numbers in steps of ten. A logger accepts a record when the record number is at least the logger level number, and drops it below that. This program sets WARNING, so the debug and info calls produce nothing:
import logging, sys
print(logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR, logging.CRITICAL)
print(logging.getLevelName(20), logging.getLevelName(40))
logger = logging.getLogger("levels")
logger.setLevel(logging.WARNING)
handler = logging.StreamHandler(sys.stdout)
handler.setFormatter(logging.Formatter("%(levelname)s: %(message)s"))
logger.addHandler(handler)
logger.propagate = False
logger.debug("hidden debug")
logger.info("hidden info")
logger.warning("shown warning")
logger.error("shown error")
print("effective level:", logger.getEffectiveLevel())
The exact output:
10 20 30 40 50
INFO ERROR
WARNING: shown warning
ERROR: shown error
effective level: 30
The getLevelName function turns a number back into its name. The getEffectiveLevel method reports the level that governs the logger: its own level when one is set, or the nearest set level above it in the name hierarchy when it is not. The level is a filter, not a label. Raising it to ERROR would leave only the error and critical lines, and the dropped calls cost almost nothing because the module never formats the message for a record that never exists, a point the arguments section below uses.
basicConfig: the one-call shortcut
Small programs skip the manual setup. The basicConfig function configures the root logger once, with a level, a destination, and a format, and every named logger sends its records up to the root handlers by default. This program sets INFO, so the debug call still produces nothing:
import logging, sys
logging.basicConfig(level=logging.INFO, stream=sys.stdout,
format="%(levelname)s %(name)s: %(message)s")
logger = logging.getLogger("app")
logger.debug("hidden debug")
logger.info("started")
logger.warning("disk almost full")
print("root level:", logging.getLogger().level)
The exact output:
INFO app: started
WARNING app: disk almost full
root level: 20
The app logger has no level of its own, so it inherits the root level of 20, and no handlers of its own, so its records propagate to the root handler that basicConfig installed. Calling getLogger with no name returns the root logger itself. The shortcut and the manual setup are the same machinery: basicConfig is a handler, a formatter, and a level placed on the root logger in one call.
Two handlers, two levels: the file keeps more than the screen
A handler carries its own level, checked after the logger level. One logger can feed two destinations that keep different amounts. Here the logger passes everything from DEBUG up, the console handler takes WARNING and above, and the file handler takes everything. The file is read back at the end, so the output shows both destinations:
import logging, sys
logger = logging.getLogger("billing")
logger.setLevel(logging.DEBUG)
console = logging.StreamHandler(sys.stdout)
console.setLevel(logging.WARNING)
console.setFormatter(logging.Formatter("CONSOLE %(levelname)s: %(message)s"))
fileh = logging.FileHandler("billing.log")
fileh.setLevel(logging.DEBUG)
fileh.setFormatter(logging.Formatter("FILE %(levelname)s: %(message)s"))
logger.addHandler(console)
logger.addHandler(fileh)
logger.propagate = False
logger.debug("invoice drafted")
logger.info("invoice sent")
logger.warning("payment late")
logger.error("card declined")
fileh.close()
print(open("billing.log").read(), end="")
The exact output:
CONSOLE WARNING: payment late
CONSOLE ERROR: card declined
FILE DEBUG: invoice drafted
FILE INFO: invoice sent
FILE WARNING: payment late
FILE ERROR: card declined
The two debug and info records exist, because the logger level let them through, and the file handler kept them while the console handler dropped them. That split is the common production shape: a quiet screen and a complete file from one set of logging calls. Each handler also holds its own formatter, so the same record can carry a short line on the screen and a longer one in the file.
Child loggers: the dotted name is a hierarchy
Dots in a logger name build a family tree. The logger named app.db is the child of the logger named app, which is the child of the root logger. A child with no level and no handlers still logs: it borrows the effective level from its parent and sends its records to the parent handlers. Only the parent gets a handler here:
import logging, sys
parent = logging.getLogger("app")
parent.setLevel(logging.INFO)
handler = logging.StreamHandler(sys.stdout)
handler.setFormatter(logging.Formatter("%(name)s %(levelname)s: %(message)s"))
parent.addHandler(handler)
parent.propagate = False
child = logging.getLogger("app.db")
print("child name:", child.name)
print("child parent is parent:", child.parent is parent)
print("child handlers:", child.handlers)
print("child effective level:", child.getEffectiveLevel())
child.debug("hidden query")
child.info("query ran")
child.warning("slow query")
The exact output:
child name: app.db
child parent is parent: True
child handlers: []
child effective level: 20
app.db INFO: query ran
app.db WARNING: slow query
The records carry the child name, app.db, even though the parent handler wrote them, so one handler serves the whole family and the lines still say which part logged them. The debug call dropped because the inherited level is INFO. The usual pattern follows from this: a library asks for a logger named after its module, the application configures the parent or the root once, and every module record flows to that one setup.
Message arguments, and logging an exception
A logging call takes a format string and separate arguments, and the module joins them only when the record is emitted. Passing values as arguments instead of building one string first keeps a dropped record cheap: a debug call under a WARNING level never builds its text. Inside an except block, the exception method logs at ERROR level and adds the current traceback after the message. This program captures the output in a text stream so it can show the first lines and confirm the traceback is present:
import io, logging
stream = io.StringIO()
handler = logging.StreamHandler(stream)
handler.setFormatter(logging.Formatter("%(levelname)s: %(message)s"))
logger = logging.getLogger("jobs")
logger.setLevel(logging.DEBUG)
logger.addHandler(handler)
logger.propagate = False
name = "ana"
count = 3
logger.info("user %s ran %d jobs", name, count)
try:
1 / 0
except ZeroDivisionError:
logger.exception("job failed")
out = stream.getvalue()
lines = out.splitlines()
print(lines[0])
print(lines[1])
print("ZeroDivisionError in output:", "ZeroDivisionError: division by zero" in out)
print("traceback in output:", "Traceback (most recent call last)" in out)
The exact output:
INFO: user ana ran 3 jobs
ERROR: job failed
ZeroDivisionError in output: True
traceback in output: True
The percent signs in the format string mark where the arguments land, in order. The exception call produced the ERROR line plus a traceback that names the ZeroDivisionError and its message, which is the record a reader needs when a job fails at night. Calling exception outside an except block logs a record whose traceback is the single line NoneType: None, so the method belongs inside the handler for the error it reports.
Three traps a first setup meets
import logging, sys
root = logging.getLogger()
print("root default level:", root.level)
logging.basicConfig(level=logging.INFO, stream=sys.stdout,
format="FIRST %(levelname)s: %(message)s")
logging.basicConfig(level=logging.DEBUG, stream=sys.stdout,
format="SECOND %(levelname)s: %(message)s")
print("root level after two calls:", root.level)
logger = logging.getLogger("trap")
logger.info("goes through the first format")
logging.basicConfig(level=logging.DEBUG, stream=sys.stdout,
format="FORCED %(levelname)s: %(message)s", force=True)
print("root level after force:", root.level)
logger.info("goes through the forced format")
The exact output:
root default level: 30
root level after two calls: 20
FIRST INFO: goes through the first format
root level after force: 10
FORCED INFO: goes through the forced format
The root level stayed at 20 after the second call, not 10, and the record printed with the first format. Only the forced call moved the level to 10 and switched the format. The third trap is the double print: a named logger with its own handler and propagation left on sends each record to its handler and then to the root handlers, so the same line lands twice. The programs in this guide set propagate to False wherever a logger holds its own handler for exactly that reason.
Which form for which job
| Job | Form | Why |
|---|---|---|
| A quick script | basicConfig with a level and a format | One call puts a handler and a formatter on the root logger |
| A module inside a larger program | getLogger with the module name | The application configures the parent once and the module records flow there |
| Keeping routine detail out of the screen but in a file | One logger, two handlers with different levels | The logger level admits the records and each handler keeps its share |
| A record that must say where it came from | The name field in the formatter | The logger name rides on every record, including child records a parent handler writes |
| Values inside a message | Arguments after the format string | The text is built only when the record is emitted, so dropped records stay cheap |
| A failure with its cause | The exception method inside an except block | The record carries the message plus the full traceback |
| Reconfiguring after a first setup | basicConfig with force=True | A plain second call is ignored once root handlers exist |
| Stopping duplicate lines | propagate = False on a logger with its own handler | The record stops at that logger instead of also reaching the root handlers |
Checklist
- Before wondering why info lines are missing, check the level: the root default is WARNING, and a logger with no level inherits from its parent.
- Before adding a handler to a logger, set propagate to False or accept that the root handlers will print the same record again.
- Before building a message string by hand, pass the values as arguments and let the module join them when the record is emitted.
- Before catching an exception in silence, log it with the exception method so the traceback lands with the message.
- Before calling basicConfig a second time to change the setup, pass force=True; without it the call does nothing.
- Before giving a destination less detail, set the level on its handler, not on the logger; the logger level governs every destination at once.
Related guides on this site
- Python Exceptions — try, except, else, finally, and raise — the try and except machinery the exception logging method sits inside, and how a traceback is built.
- Python Modules and Packages — import, Aliases, and name — the module naming that logger names usually follow, one logger per module.
- Python Files — open, read, write, and with — the file handling behind the FileHandler destination that keeps the complete record set.
- Python Classes and Objects — init, Methods, Inheritance, and Dataclasses — the class machinery behind loggers, handlers, and formatters, which are objects with methods the module calls.
Sources
- Python Standard Library, logging — getLogger and the logger hierarchy, the five level names and numbers, handlers and their levels, Formatter fields, basicConfig and its force argument, propagate, and the exception method.
- Python Logging HOWTO — the basic and advanced logging tutorials, basicConfig use, message arguments, and handler setup for libraries and applications.
Keep Exploring
The full Python hub \u2014 language basics, the standard library, and data tools.
Every guide on the site in one list, grouped by topic.
Every browser-only checker and verifier on the site.
The C++, Python, Sysadmin, Rust, Go, and TypeScript hubs.