Back to Explore
GuideVibeFix editorialUpdated Nov 23, 2026

Python Logging in Practice: Stop Debugging with print

print can only show things; logging grades them by severity, adds the time, writes to a file and stays readable afterwards. Levels, formats, rotation, dictConfig and the three duplicate-log traps — every example actually run on Python 3.12.3.

Real photo: an open handwritten notebook on a wooden desk, a cup of coffee and a pen beside it

The till program at Morning Light Bookshop has a problem: yesterday's takings came out two hundred yuan short. The shop assistant opens the code and finds print statements everywhere — the purchase price printed, every order printed, "got this far" printed. But when it comes to finding the problem, all those prints are useless: there is no way to tell which lines are from yesterday and which are from today; debugging noise and real errors are mixed together on one screen; and once the program closes, all the output is gone, so yesterday's scene cannot be replayed.

That is the ceiling of debugging with print: it can only show things, with no record of when they happened, how important they are, or whether they can be found afterwards. Python's standard library has a module made for exactly this job, called logging, and it ships with Python. What it does comes down to four things: give every message a severity so only the ones that matter are kept; attach the time, the name and the origin to every message; send messages to the screen, to a file, or both; and keep the records in a file after the program finishes so they can be read later. This guide shows how to use it: levels, formats, files, rotation, configuration, and the three traps that make beginners' logs print twice. Every code sample was actually run on Python 3.12.3 and every output quoted is a real result; the bookshop in the examples is fictional, the code and the numbers are real.

First, the default behaviour: INFO and DEBUG are invisible by default

Many people's first experience with logging goes like this: they write logging.info, nothing appears on screen, and they assume the module is broken. It is not broken — the default level is filtering it out. logging has five levels, lightest to heaviest: DEBUG, INFO, WARNING, ERROR and CRITICAL, with the numbers 10, 20, 30, 40 and 50. The root logger's default level is WARNING, which means only WARNING and above are shown, while DEBUG and INFO are silently dropped. Here is the default behaviour, measured:

import logging

logging.info("info: shop opens at 9")
logging.warning("warning: stock of pens is low")
logging.error("error: failed to save the report")

The measured output is only two lines:

WARNING:root:warning: stock of pens is low
ERROR:root:error: failed to save the report

The info line ran, but nothing printed, because its level of 20 never reached the default threshold of 30. The output format is worth a look too: WARNING:root:... is the level, then the logger name root, then the message. That is the default format Python gives you with no configuration at all. The levels mean "how serious is this": DEBUG is detail for use while developing, INFO is "the program got this far in its normal course", WARNING is "something looks off but it still runs", ERROR is "this step failed", and CRITICAL is "the whole program is about to fall over". Deciding the level of a message before you write it saves far more time than digging through a wall of output afterwards.

basicConfig only works before the first log message

Once you know about the default level, the next step is to change the configuration: lower the threshold, change the format. The usual way is logging.basicConfig, called once at the start of the program:

logging.basicConfig(level=logging.DEBUG, format="%(levelname)s %(message)s")

But there is a trap most beginners walk into: basicConfig only takes effect while the root logger has no handler yet. The moment you log a first message, Python quietly attaches a default handler to the root logger, and calling basicConfig after that changes nothing. I measured this deliberately, logging first and configuring second:

logging.info("info: shop opens at 9")        # logged first: the default handler is now attached
logging.basicConfig(level=logging.DEBUG, format="%(levelname)s %(message)s")
logging.debug("debug after late basicConfig: still invisible?")
logging.info("info after late basicConfig: still invisible?")

The measured output: the debug and info lines still never appeared. The late basicConfig did nothing at all. The rule is one sentence: basicConfig must be called before the first log message in the program — usually the first line of main, or right after the imports. If you change the configuration and nothing happens, check whether something already logged before you: very often a module logs a line while it is being imported, and that beats you to installing the default handler.

The four parts: Logger, Handler, Formatter, Filter

logging is built from four parts, and once you understand what each one does, every configuration makes sense. A Logger is the object your code logs to; it decides whether a message is important enough to pass on. A Handler sends the message somewhere — the screen, a file, a network socket. A Formatter arranges the message the way you want it. A Filter does finer-grained screening, and is rarely needed day to day — it is enough to know it exists.

The rule for writing code is: at the top of each module, take a logger named after that module, and do not log straight to the root logger with logging.info everywhere. The official docs recommend logging.getLogger(__name__), and calling it several times with the same name always returns the same logger object. Here is a logger with its own format, measured:

logger = logging.getLogger("bookshop")
logger.setLevel(logging.DEBUG)
h = logging.StreamHandler()
h.setFormatter(logging.Formatter("%(levelname)s %(name)s: %(message)s"))
logger.addHandler(h)
logger.propagate = False
logger.debug("debug: opening the ledger")
logger.info("info: sold 3 books")
logger.warning("warning: only 2 pens left")

The measured output:

DEBUG bookshop: debug: opening the ledger
INFO bookshop: info: sold 3 books
WARNING bookshop: warning: only 2 pens left

In the format, %(levelname)s is the level, %(name)s is the logger name, and %(message)s is the message itself. Other useful fields are %(asctime)s for the time, %(filename)s for the file name, %(lineno)d for the line number, and %(funcName)s for the function name. When you are debugging a live problem, time plus module name plus line number are the three fields that matter most — without a time, you cannot match a log line to the moment something went wrong. What propagate = False does is covered in the section on duplicate logs below.

Levels have two gates: the logger's and the handler's

Setting the logger's level alone is not enough, because level checks happen at two gates. The first gate is the logger's level; the second is the handler's level, and a message has to pass both before it is printed. The logger's level decides "is this message worth passing on", and the handler's level decides "now that it is here, do I print it". I measured the combination with the logger at DEBUG and the handler at WARNING:

logger.setLevel(logging.DEBUG)
h.setLevel(logging.WARNING)
logger.debug("debug: filtered by handler")
logger.info("info: filtered by handler")
logger.warning("warning: passes the handler")

The measured output is a single line:

WARNING bookshop: warning: passes the handler

The debug and info messages passed the logger's gate and were stopped at the handler's gate. The practical use is this: one logger can have two handlers, one writing to the screen at WARNING so you only see serious problems, and one writing to a file at DEBUG so everything is recorded. The screen stays clean and the file has the full story. It works the other way round too: if the logger's level is high, setting the handler's level low achieves nothing, because the message is dropped at the first gate. When you are wondering "why is my log not appearing", check both gates — checking only one sends you down the wrong path.

Three traps that print every log twice

The strangest thing in logging is seeing the same message twice, or three times. There are three causes, each measured below.

The first trap: a setup function called twice. Many projects have a setup_logging function that creates a handler and attaches it to a logger. If that function runs twice while the program starts, the logger ends up with two different handlers, and one message passes through two handlers and prints twice:

def setup_till():
    lg = logging.getLogger("till2")
    lg.setLevel(logging.INFO)
    hh = logging.StreamHandler()
    hh.setFormatter(logging.Formatter("%(levelname)s %(name)s: %(message)s"))
    lg.addHandler(hh)
    lg.propagate = False
    return lg

till2 = setup_till()
till2 = setup_till()  # called again by mistake: a second, new handler is attached
till2.info("info: setup called twice, new handler each time")

The measured output shows the line twice:

INFO till2: info: setup called twice, new handler each time
INFO till2: info: setup called twice, new handler each time

The fix is to check whether the logger already has a handler before attaching one, or to write the setup function so it only runs once. As a side note, attaching the same handler object twice does not duplicate anything: I measured attaching the same h to the logger twice, and the message appeared only once, because addHandler silently ignores an object that is already attached. Duplication always comes from different handler objects attached several times — not from attaching several times as such.

The second trap: propagation. By default, a logger passes its messages upwards: a child logger's message goes through its own handlers and is also handed to the handlers of its parent loggers and the root logger. The official docs say it plainly: if you attach a handler to a logger and to one or more of its ancestors, the same record may be emitted several times. I measured a minimal case, with a handler on the root logger and one on the child logger shop.sales:

logging.basicConfig(level=logging.INFO, format="ROOT %(levelname)s: %(message)s")
child = logging.getLogger("shop.sales")
child.setLevel(logging.INFO)
h = logging.StreamHandler()
h.setFormatter(logging.Formatter("CHILD %(levelname)s: %(message)s"))
child.addHandler(h)
child.info("sold a book")

The measured output:

CHILD INFO: sold a book
ROOT INFO: sold a book

One message printed twice — once by the child logger's own handler, once by the root logger's handler further up the propagation chain. Setting child.propagate to False and logging again leaves only the child handler's copy. In my run the second line, "sold a pen", appeared exactly once: CHILD INFO: sold a pen. The rule is: either attach handlers only to the highest logger and let propagation do the work, or attach a handler to a child logger and switch propagate off. Attaching on both sides with propagation left on always duplicates. That is why the bookshop logger above sets propagate = False.

The third trap: mixing basicConfig with handlers you attach yourself. basicConfig attaches a handler to the root logger; if you then attach another handler to a child logger and leave propagation on, the result is the same doubling as in the second trap. The fix is the same choice between two options: for a small project, basicConfig on the root logger alone is enough; for a larger one, configure everything at once with dictConfig and do not mix half basicConfig with half manual setup.

The diagram below draws the whole chain: a message leaves the logger, passes the logger-level gate, then the handler-level gate, and is finally formatted and delivered to the screen or to a file.

The path of a log record from logger to output: the logger filters by level, then the handler filters by level, then the formatter lays it out for the screen or a file

When something raises: do not just log one line, log the scene

When a program raises an exception, logging only "daily total failed" is useless — afterwards you have no idea which line failed. The right approach is logger.exception inside the except block, which appends the full traceback to the message automatically:

try:
    1 / 0
except ZeroDivisionError:
    logger.exception("error: daily total failed")

The measured output:

ERROR bookshop: error: daily total failed
Traceback (most recent call last):
  File "/tmp/log240/demo_en.py", line 44, in <module>
    1 / 0
    ~~^~~
ZeroDivisionError: division by zero

(The file path and line number in the traceback are from your own run; the ones above are from this measured run, and yours will show your own file.) The traceback gives you the file, the line, the exact code and the exception — everything you need to reproduce the problem, and far faster than guessing from memory. The same effect can be written as logger.error("...", exc_info=True); exception is shorthand for error with exc_info=True, as the official docs describe it. One more small habit: do not build the message with an f-string first. Write logger.info("sold %s books", 3) in "format plus arguments" form, and when the level is not high enough to print, even the string-building work is skipped.

Writing to a file: logs must not live only on the screen

Logs on the screen are gone the moment the program closes. To debug something afterwards, they have to go into a file. The simplest way is to pass a filename to basicConfig, or attach a FileHandler:

logging.basicConfig(filename="shop.log", level=logging.INFO)

But a file grows forever, and one day it fills the disk. Production setups therefore use RotatingFileHandler: when the file reaches a size limit, a new file is started, the old ones are kept numbered, and once the number of backups is exceeded the oldest is deleted. I measured rotation with small numbers — at most 200 bytes per file, 2 backups kept, 12 order records written:

from logging.handlers import RotatingFileHandler

fh = RotatingFileHandler("logs/shop.log", maxBytes=200, backupCount=2, encoding="utf-8")
fh.setFormatter(logging.Formatter("%(levelname)s %(message)s"))
flog = logging.getLogger("shopfile")
flog.setLevel(logging.INFO)
flog.addHandler(fh)
flog.propagate = False
for i in range(12):
    flog.info(f"order {i:02d}: sold a book for $59.9")
fh.close()

After the measured run, the directory held three files, each with its own share of the records:

shop.log   size 74 bytes   2 lines  first: INFO order 10: sold a book for $59.9
shop.log.1 size 185 bytes  5 lines  first: INFO order 05: sold a book for $59.9
shop.log.2 size 185 bytes  5 lines  first: INFO order 00: sold a book for $59.9

The pattern is clear: when the file is about to pass 200 bytes it rolls over, the file being written is always shop.log, and older ones are renamed to .1 and .2; with backupCount=2 only two backups are kept, and anything older than that is deleted. Twelve records at 37 bytes each come to 444 bytes, split across the three files. In a real project maxBytes is usually a few megabytes and backupCount 5 to 10; for rotation by day there is TimedRotatingFileHandler, and the official docs cover both with equally straightforward parameter names. Remember to close the handler when you are done, or let the program exit normally so it closes itself — otherwise the last few lines may still be sitting in the buffer, unwritten.

One dictionary for everything: dictConfig

When a project grows, basicConfig runs out of room: several modules, several destinations, different levels. Python offers logging.config.dictConfig, which configures everything at once from a dictionary. The dictionary can live in the code or in a config file that changes with the deployment environment:

import logging.config

logging.config.dictConfig({
    "version": 1,
    "formatters": {"plain": {"format": "%(levelname)s %(name)s: %(message)s"}},
    "handlers": {"console": {"class": "logging.StreamHandler",
                             "formatter": "plain", "level": "INFO"}},
    "loggers": {"till": {"handlers": ["console"], "level": "DEBUG",
                         "propagate": False}},
})
till = logging.getLogger("till")
till.debug("debug: till logger level DEBUG but handler INFO")
till.info("info: till opened, cash $500")

The measured output is only the info line:

INFO till: info: till opened, cash $500

The debug line passed the logger's DEBUG gate and was stopped by the handler's INFO gate, exactly as the two-gates section described. The version in the dictionary must be 1 — that is the version number of the dictionary schema, and it is currently the only value available. The formatters, handlers and loggers blocks define the formats, the destinations and the loggers, and a handler's class is written as its full dotted name, such as logging.StreamHandler or logging.handlers.RotatingFileHandler. Once configured, the code only takes a logger and logs; where messages go and at what level is all decided in the dictionary, without touching the business code.

Using dictConfig has one more easily missed benefit: the same configuration can be swapped between development and production. In development, set the console handler's level to DEBUG and see everything; in production, change it to WARNING so the screen only shows what really matters, while the file handler stays at DEBUG and keeps the detail in the file. Once the configuration is pulled out of the code, changing a level, adding a file or changing a format no longer means editing code and redeploying the business logic — whoever operates the service just edits the config file. That is why any project beyond a small one is better off with dictConfig than with basicConfig: basicConfig lives in the code, so every change means a code change and a new release, while a dictionary configuration is data, and far more flexible.

When to use print and when to use logging

After learning logging, should print never be used again? No. print fits one-off debugging that you throw away afterwards: checking whether a value is right, confirming the program reached a certain point, and then deleting the line. logging fits things that should stay, be graded by severity, and be found afterwards: the running record of a program once it is live, the scene of a failure that needs reproducing, and information that has to be filtered by level. A short comparison: use print to take a quick look at something once; use logging to keep something for later; use logging to say "this matters, that does not"; use logging to write to the screen and a file at the same time; and use logging when a program will be used and deployed by other people.

There is one more step beyond this guide, but it belongs to a different article: structured logging — recording logs as JSON or another machine-readable format so they can be collected centrally and searched. This site already has a hands-on guide to structured logging, covering how to record logs as structure, how to search them, and which traps to avoid. This guide covers the basics of the standard library logging module, and the two articles divide the work as "first learn to keep a log, then keep it as structure". If you have worked through the four parts, the two gates and the three traps here, that guide will feel like a natural next step.

Wrap-up: a checklist

Run through this list when you wire logging into your own project: call basicConfig before the first log message; take a logger per module with getLogger(__name__); put at least the time, the level and the module name in the format, so a line can be matched to the moment something went wrong; think about the level before you write the message — DEBUG for development detail, INFO for normal progress, WARNING for something off, ERROR for a failure; check both the logger's level and the handler's level; run the setup function once, or check whether the logger already has a handler before attaching one; if you attach a handler to a child logger, switch propagate off — or attach only to the root logger and let propagation do the work; log exceptions with logger.exception, not with a single bare sentence; write logs to a file, rotate the file, and size maxBytes and backupCount to the disk you have; and switch to dictConfig once the project grows, with one dictionary for the whole setup. With all of that in place, print can go back to the job it is good at: a tool for taking a quick look, not the only way to debug.

For practice, take one of your own small projects and replace its prints with logging, one step at a time: add basicConfig at the top with the level at INFO; swap each module's prints for info and warning calls from getLogger(__name__); attach a RotatingFileHandler so logs go into a file as well; then deliberately write a place that raises, run it with logger.exception, and check that the full traceback appears in the file. Once that all works, you have a logging skeleton that can grow with the project — adding features, changing deployments and tracking down problems will not need this part to be rebuilt.

Views 0Comments 0

Comments (0)

ME
0/1000
Loading comments...

Sources

Browse projectsPublish your project

Related articles