Python Logging and Debugging: Levels, Handlers, logger.exception and breakpoint()
print shouts and forgets; logging writes a logbook. The five levels, basicConfig formats, one message's path through record, handler and formatter, named loggers, logger.exception, then breakpoint(), PyCharm and assert for hunting bugs.
What you will learn
- Replace print with logging and filter messages with the five levels
- Format log lines with basicConfig and send them to the console and a file with handlers
- Use named loggers with __name__ and log errors with logger.exception
- Debug with breakpoint(), the PyCharm debugger and assert
Before you start
- try and except, and raising errors
- Importing your own module
You can already catch an error and raise one. But when a program runs without you watching, how do you know what happened? That's what logging answers.
Think about a night guard in a big building. One guard shouts everything he notices: every door, every light, every small noise. By morning nobody knows what he said. Another guard writes in a logbook, with the time and how serious each thing is. In the morning you open it, skip the small stuff and go straight to the broken window. print is the shouting. Logging is the logbook.
The problem with print
def process_orders(orders):
print("Starting order processing...")
total = 0
for order in orders:
print(f"Processing: {order}")
try:
amount = float(order["amount"])
total += amount
print(f" Added {amount}")
except (ValueError, KeyError) as e:
print(f" ERROR: {e}")
print(f"Total: {total}")
return total
orders = [{"amount": "12.50"}, {"amount": "abc"}]
process_orders(orders)
Starting order processing...
Processing: {'amount': '12.50'}
Added 12.5
Processing: {'amount': 'abc'}
ERROR: could not convert string to float: 'abc'
Total: 12.5
Every message comes out every time, and there's no way to turn some of them off. The error line looks like all the others. It's only on the console, with no time and no line number. So you end up adding prints, deleting them, then adding them again.
Five levels, one gate
import logging
levels = [logging.DEBUG, logging.INFO, logging.WARNING,
logging.ERROR, logging.CRITICAL]
for level in levels:
print(level, logging.getLevelName(level))
10 DEBUG
20 INFO
30 WARNING
40 ERROR
50 CRITICAL
Debug is the small detail you need while fixing something. Info is things going as planned. Warning means something looks wrong but the program carries on. Error means something failed. Critical means the whole program is in trouble. You choose a level, and only messages with that number or higher get through.
import logging
logging.debug("Variable x = 42")
logging.info("Server started on port 8080")
logging.warning("Disk space below 10%")
logging.error("Failed to connect to DB")
logging.critical("System out of memory")
WARNING:root:Disk space below 10%
ERROR:root:Failed to connect to DB
CRITICAL:root:System out of memory
With nothing configured, the gate sits at warning (30), so debug and info are dropped. Each line shows the level, the logger name (root here) and the message.
Moving the gate with basicConfig
import logging
import sys
logging.basicConfig(
level=logging.DEBUG,
format="%(levelname)s: %(message)s",
stream=sys.stdout,
)
logging.debug("Variable x = 42")
logging.info("Server started on port 8080")
logging.warning("Disk space below 10%")
logging.error("Failed to connect to DB")
logging.critical("System out of memory")
DEBUG: Variable x = 42
INFO: Server started on port 8080
WARNING: Disk space below 10%
ERROR: Failed to connect to DB
CRITICAL: System out of memory
Change one word to level=logging.WARNING and you're back to three lines, without touching a single message. That's why you keep debug messages in the code: turn them on while you fix a bug, and leave them quiet the rest of the time. Logging writes to standard error by default; stream=sys.stdout keeps it with the normal output.
What each line looks like
import logging
import sys
logging.basicConfig(
level=logging.DEBUG,
format="%(asctime)s [%(levelname)-8s] "
"%(filename)s:%(lineno)d - %(message)s",
datefmt="%H:%M:%S",
stream=sys.stdout,
)
logging.debug("App initialized")
logging.info("Processing %d items", 42)
logging.warning("Cache miss for key: %s", "user_1")
15:08:26 [DEBUG ] basic_config.py:12 - App initialized
15:08:26 [INFO ] basic_config.py:13 - Processing 42 items
15:08:26 [WARNING ] basic_config.py:14 - Cache miss for key: user_1
%(asctime)s is the time, %(levelname)-8s pads the level to eight characters so the columns line up, and %(filename)s:%(lineno)d says where the message came from: line 12 in the code is line 12 in the output. Add %(name)s and %(funcName)s and a line can read INFO | root | checkout | Cart has 3 items. Every line now tells you when, how serious and where.
One message's path through logging
When you call logger.info("Order %d paid", 7), the logger checks its level first. If the message passes, Python packs it into a log record holding the level, logger name, line number and message. The record goes to a handler, whose job is to send it somewhere. A tiny custom handler that prints the record's fields shows it:
import logging
class Show(logging.Handler):
def emit(self, record):
print(record.levelname, record.name)
print("line", record.lineno)
print(record.getMessage())
logger = logging.getLogger("shop")
logger.setLevel(logging.INFO)
logger.addHandler(Show())
logger.info("Order %d paid", 7)
INFO shop
line 15
Order 7 paid
That order explains a small habit: pass values with %s, not an f-string. In the lesson's lazy_format.py, a class prints "formatting now" whenever it's turned into text, the level is warning, and two debug calls are dropped. The %s version never gets formatted. The f-string version is built before logging even gets the call, so "formatting now" prints once. A dropped %s message costs almost nothing.
Handlers: short on the console, full in a file
import logging
import sys
logger = logging.getLogger("myapp")
logger.setLevel(logging.DEBUG)
console_h = logging.StreamHandler(sys.stdout)
console_h.setLevel(logging.INFO)
console_h.setFormatter(
logging.Formatter("[%(levelname)s] %(message)s"))
file_h = logging.FileHandler("app.log")
file_h.setLevel(logging.DEBUG)
file_h.setFormatter(logging.Formatter(
"%(asctime)s [%(levelname)-8s] %(name)s: %(message)s",
datefmt="%H:%M:%S"))
logger.addHandler(console_h)
logger.addHandler(file_h)
logger.debug("Cache warmed")
logger.info("Server started")
logger.warning("Disk space low")
print("--- app.log ---")
file_h.close()
print(open("app.log").read().rstrip())
[INFO] Server started
[WARNING] Disk space low
--- app.log ---
15:08:27 [DEBUG ] myapp: Cache warmed
15:08:27 [INFO ] myapp: Server started
15:08:27 [WARNING ] myapp: Disk space low
One logger, two handlers, each with its own level and format. "Cache warmed" passes the logger, but the console handler's gate is at info, so only the file takes it. The console stays clean, and the file has everything.
Named loggers
import logging
import sys
logging.basicConfig(
level=logging.DEBUG,
format="%(name)s [%(levelname)s] %(message)s",
stream=sys.stdout,
)
app = logging.getLogger("myapp")
db = logging.getLogger("myapp.database")
print(db.parent.name)
app.info("App started")
db.info("Connecting to localhost:5432")
myapp
myapp [INFO] App started
myapp.database [INFO] Connecting to localhost:5432
The dot makes myapp.database a child of myapp. Messages climb up to the root logger, where basicConfig put its handler, and every line tells you which part of the program wrote it. Names also give you a volume control: logging.getLogger("myapp.database").setLevel(logging.WARNING) keeps the database's info messages quiet while its warnings and everything else still come through.
In real code, write logger = logging.getLogger(__name__) at the top of each module. __name__ is the module's name, so a logger in shop_db.py is called shop_db. The module only creates its logger and logs; the file that runs the program calls basicConfig, once. Running the lesson's use_shop_db.py prints:
__main__
shop_db
shop_db [INFO] Connecting to localhost:5432
Logging errors with logger.exception
import logging
import sys
logging.basicConfig(
level=logging.DEBUG,
stream=sys.stdout,
)
logger = logging.getLogger(__name__)
def divide(a, b):
try:
return a / b
except ZeroDivisionError:
logger.exception("Division failed")
return None
print(divide(10, 0))
ERROR:__main__:Division failed
Traceback (most recent call last):
File "S04L02_Logging/log_exception.py", line 13, in divide
return a / b
~~^~~
ZeroDivisionError: division by zero
None
logger.exception logs at error level and adds the whole traceback by itself, and the program carries on. Call it only inside an except block. A plain logger.error gives you one line with no traceback; logger.error(..., exc_info=True) brings it back. So exception is really error with exc_info=True, and you reach for exc_info when you want the traceback at another level, like warning.
When you need the traceback as text, to save in a database or put in an email, use the traceback module. traceback.format_exc() returns it as a string (five lines for a 1 / 0, ending ZeroDivisionError: division by zero), and traceback.print_exc() prints it.
Hunting a bug: four moves
- Read the traceback, starting from the last line. That's the reason.
- Add debug logs around the problem and turn them on.
- Pause the program at a breakpoint and look at the values.
- Write an
assert, so the mistake can't slip past quietly.
breakpoint() and pdb
def average(nums):
total = 0
for n in nums:
total += n
return total / len(nums)
scores = [80, 90, 70]
breakpoint()
print(average(scores))
The program stops on line 9 with a (Pdb) prompt. Typing p scores, n, s, p nums, w and c gives:
> S04L02_Logging/debug_me.py(9)<module>()
-> breakpoint()
(Pdb) [80, 90, 70]
(Pdb) > S04L02_Logging/debug_me.py(10)<module>()
-> print(average(scores))
(Pdb) --Call--
> S04L02_Logging/debug_me.py(1)average()
-> def average(nums):
(Pdb) [80, 90, 70]
(Pdb) S04L02_Logging/debug_me.py(10)<module>()
-> print(average(scores))
> S04L02_Logging/debug_me.py(1)average()
-> def average(nums):
(Pdb) 80.0
p prints a value, n runs one line, s steps inside a function, w shows where you are and who called you, and c continues. Remove the breakpoint when you're done. PyCharm gives you the same with buttons: click in the gutter for a red dot, start with the bug icon, watch the Variables panel, and use Step Into, Step Over and Resume. Your code doesn't change.
assert
def average(nums):
assert len(nums) > 0, "nums must not be empty"
return sum(nums) / len(nums)
print(average([80, 90, 70]))
print(average([]))
80.0
Traceback (most recent call last):
File "S04L02_Logging/assert_check.py", line 7, in <module>
print(average([]))
~~~~~~~^^^^
File "S04L02_Logging/assert_check.py", line 2, in average
assert len(nums) > 0, "nums must not be empty"
^^^^^^^^^^^^^
AssertionError: nums must not be empty
Without it this would fail a line later with a confusing division by zero. Use assert for your own mistakes while developing, not for checking user input, because Python can switch asserts off. For bad input, raise a proper error.
The orders program, with logging
import logging
import sys
logger = logging.getLogger(__name__)
def process_orders(orders):
logger.info("Starting order processing")
total = 0
for order in orders:
logger.debug("Processing: %s", order)
try:
amount = float(order["amount"])
total += amount
except (ValueError, KeyError):
logger.exception("Bad order: %s", order)
logger.info("Total: $%.2f", total)
return total
debug = "debug" in sys.argv
level = logging.DEBUG if debug else logging.INFO
logging.basicConfig(
level=level,
format="%(levelname)s: %(message)s",
stream=sys.stdout,
)
process_orders([{"amount": "12.50"}, {"amount": "abc"}])
Run with python orders_after.py debug:
INFO: Starting order processing
DEBUG: Processing: {'amount': '12.50'}
DEBUG: Processing: {'amount': 'abc'}
ERROR: Bad order: {'amount': 'abc'}
Traceback (most recent call last):
File "S04L02_Logging/orders_after.py", line 13, in process_orders
amount = float(order["amount"])
ValueError: could not convert string to float: 'abc'
INFO: Total: $12.50
Without the word debug, the two "Processing" lines disappear. We didn't edit one message; one level changed what we see. You can prompt an AI tool with one line, "replace print with logging and use a named logger", then read what it gives you.
Try it yourself
Add a file handler at warning level to a shop logger, log an info message and then an exception from int("ten"), and check that the first line of shop.log is ERROR: Bad quantity.
Related course on Udemy
The Python Architect Masterclass: Full Stack to AI Engineer
Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)Related posts
Set Up a Python AI Project with uv, VS Code and an API Key in .env
One environment for every AI project: uv brings Python 3.12 and pinned packages from uv.lock, a check script fails four times on plain python and passes after uv sync, VS Code points at .venv, the API key stays in .env, and a stand-in test model answers when there is no key.
uv and pyproject.toml: Start, Add, Run and Rebuild a Python Project
One tool instead of venv, activate, pip install and pip freeze. Build a small chatbot project with uv init, hit ModuleNotFoundError, fix it with uv add, read pyproject.toml and uv.lock, then delete .venv and rebuild it with uv sync.
Python try and except Basics: Catch an Error and Keep Going
An exception is the object Python creates when something goes wrong. Catch it with try and a named except, read it with as, add else and finally, retry bad input in a loop, and see why a bare except hides your bugs.
Read and Write a File in Python: open, with, Modes and Encoding
Make your data outlive the program: write notes.txt with open and with, read it back three ways, see how w wipes a file and a appends, why encoding matters, and what to do when a file isn't there.
