Quick answer
Python's logging module records what your program does while it runs, at levels from DEBUG to CRITICAL, and sends those records to the console, a file, or both. One named logger with a console handler and a rotating file handler gives you a readable record of every order, warning, and failed payment. This post builds that setup for a small Karachi shop orders script, shows real output, and fixes the duplicate lines that catch almost everyone.
A shop in Karachi takes orders on WhatsApp and in a notebook. One evening a customer pays, the payment fails, and nobody can say when or why, because the script printed a few lines and the screen scrolled away. Print statements feel fast, until the one line you need is gone. That is when logging earns its place: a written record that survives the terminal, with a level on every line so an everyday order reads differently from a failed payment. The rest of this post builds that record with a script you can run yourself.
What I would check before using it
My first check is whether print is enough. For a script you run once and throw away, print is fine. For anything that handles money, orders, or customers, it is not: print has no levels, no timestamps, and no file to check tomorrow. Logging costs about ten lines of setup and gives you all three.
My second check is the levels. The default is WARNING, so INFO lines silently vanish unless you set the level. Decide the levels up front: INFO for normal events like an order placed, WARNING for low stock, ERROR for a declined card. If everything is INFO, the log is noise; if everything is ERROR, nobody believes the errors.
My third check is where the logs live: the console for watching a run live, a file for looking back after a customer complains. I use both, and I rotate the file so it never grows without limit. A file that grows forever will fill a disk one quiet night, and the FastAPI Explained: Python APIs at Full Speed post applies the same console plus file setup to an API server.
My fourth check is who configures the logger. Set it up once, at the start of the program, in one place. When two parts of a program each add a handler, every line prints twice, and the worked example below shows exactly that happening.
My verdict, as judgement: adopt the logging module for any Python script that runs more than once or touches money. It flips for a genuine throwaway script, or when logs from many services need one central place to search, which is a job for a log aggregator, not a file on one machine.
A Karachi shop orders script, logged properly
The demo is a small shop orders script with two orders, one low-stock warning, and one failed payment. The setup creates a named logger with a console handler and a rotating file handler, configured exactly once:
import logging from logging.handlers import RotatingFileHandler logger = logging.getLogger("shop") logger.setLevel(logging.INFO) logger.propagate = False formatter = logging.Formatter( "%(asctime)s %(levelname)s %(name)s: %(message)s", datefmt="%H:%M:%S" ) console = logging.StreamHandler() console.setFormatter(formatter) logger.addHandler(console) file_handler = RotatingFileHandler( "orders.log", maxBytes=1_000_000, backupCount=3 ) file_handler.setFormatter(formatter) logger.addHandler(file_handler) The orders use the three levels: a warning for low stock, an info line for each order, and the failed payment with its full traceback:
STOCK = {"Wool Shawl": 12, "Cotton Kurta": 8, "Embroidered Lawn Suit": 2} class PaymentError(Exception): pass def charge_payment(order_id, amount_rs): if order_id == "1041": raise PaymentError(f"card declined for order {order_id}, Rs {amount_rs}") logger.info("Payment received for order %s, Rs %d", order_id, amount_rs) def place_order(order_id, item, qty, price_rs): if STOCK[item] <= 2: logger.warning("Low stock: %s has only %d left", item, STOCK[item]) STOCK[item] -= qty logger.info("Order %s: %d x %s, Rs %d", order_id, qty, item, qty * price_rs) try: charge_payment(order_id, qty * price_rs) except PaymentError: logger.exception("Payment failed for order %s", order_id) Before the fix, my first version printed every line twice. The bug was in the setup: I called logging.basicConfig, which adds a handler to the root logger, then added my own handler to the named logger. Each record went to my handler and then, because loggers pass records upward, to the root handler as well:
logging.basicConfig( level=logging.INFO, format="%(levelname)s %(name)s: %(message)s", ) logger = logging.getLogger("shop") console = logging.StreamHandler() logger.addHandler(console) 03:02:11 INFO shop: Order 1041: 2 x Wool Shawl, Rs 3600 INFO shop: Order 1041: 2 x Wool Shawl, Rs 3600 The fix is one line, logger.propagate = False, plus configuring the logger once instead of mixing basicConfig with a named logger:
03:02:11 INFO shop: Order 1041: 2 x Wool Shawl, Rs 3600 03:02:11 ERROR shop: Payment failed for order 1041 Traceback (most recent call last): File "shop_orders.py", line 42, in place_order charge_payment(order_id, qty * price_rs) File "shop_orders.py", line 32, in charge_payment raise PaymentError(f"card declined for order {order_id}, Rs {amount_rs}") PaymentError: card declined for order 1041, Rs 3600 03:02:11 WARNING shop: Low stock: Embroidered Lawn Suit has only 2 left 03:02:11 INFO shop: Order 1042: 1 x Embroidered Lawn Suit, Rs 3200 03:02:11 INFO shop: Payment received for order 1042, Rs 3200 The same lines landed in orders.log, so the record survives after the terminal closes. The file handler rotates when orders.log passes 1,000,000 bytes and keeps three old files, enough history for a small shop without ever filling the disk.
Common mistakes and how to fix them
First, duplicate lines from double configuration. The symptom is every line appearing twice, once with a timestamp, once without. The fix is to configure the logger once and set propagate to False, or drop basicConfig and keep only the named logger setup.
Second, INFO lines that never appear. The symptom is a log that shows only warnings and errors. The fix is logger.setLevel(logging.INFO) on the logger, because the default level is WARNING.
Third, calling logger.exception outside an except block. The symptom is a traceback that ends with "NoneType: None" instead of the real error. The fix is to call logger.exception only inside except, or logger.error with exc_info=True if you already hold the exception.
Fourth, a log file that grows forever. The symptom is a multi-gigabyte log file. The fix is RotatingFileHandler with maxBytes and backupCount, as in the worked example, instead of a plain FileHandler.
Frequently Asked Questions
Why use logging instead of print? Print writes to the screen and is gone when the terminal closes. Logging adds a level, a timestamp, and a destination, so you can keep a file and filter it later. A script that runs once can use print; anything that runs again is safer with logging.
How do I log to a file in Python? Add a FileHandler or a RotatingFileHandler to your logger and give it a formatter, as in the worked example. Both handlers can share one formatter.
How do I stop duplicate log lines? Configure the logger once, in one place. Mixing basicConfig with a handler on a named logger handles each record twice. Set propagate to False, or pick one route and stay with it.
What does propagate do? A logger passes each record up to its parents, ending at the root, unless propagate is False. That helps when the root owns the only handler, and it duplicates lines when both a child and the root have handlers.
Can I test code that uses logging? Yes. The Pytest Tutorial: Test a Real Shop Orders App in Python post tests a shop orders app, and pytest captures log records with the caplog fixture, so you can assert the warning was logged.
What to remember
- Use logging, not print, for anything that runs more than once or touches money.
- Set the level explicitly, or INFO lines will silently disappear.
- Configure the logger once, and set propagate to False when you add your own handlers.
- Log to the console for watching and a rotating file for history.
- Use logger.exception inside except blocks so failures keep their full traceback.
Where this leaves you
Two orders, one warning, one failed payment, and the whole evening is now written down in orders.log instead of lost when the terminal closed. The setup is ten lines of standard library code, no new dependency, and the duplicate-lines bug took one line to fix. If your own scripts still print their way through the day, add this logger to one of them, run it twice, and check the file the next morning before you trust it with orders that matter.
Further reading
- Python logging documentation
- Python logging HOWTO
- FastAPI Explained: Python APIs at Full Speed
- Pytest Tutorial: Test a Real Shop Orders App in Python
- Python asyncio: Running Jobs at the Same Time Without Threads
- Django REST Framework Tutorial: A Real Shop Orders API
Waqas Shahid is a software engineer from Karachi with more than 12 years of experience, including 6+ years in engineering leadership. He writes The Practical Developer.
Originally published at https://practicaldevblog.blogspot.com/2026/12/python-logging-tutorial.html
