Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

Python
  • Python for AI: The Five Tools You Actually Need
  • Thinking Like a Python Architect in an AI-First World
  • Your First Python Program: print, Comments, sep and end
  • Set Up PyCharm for Python: Install, First Project and First Run
  • Run a Python File and Read the Error: Tracebacks in Three Steps
  • Python Data Types, Variables and Strings: Indexing, Slicing and f-strings
  • Python Operators: Arithmetic, Comparison, Logical, Membership, Identity and Precedence
  • Python Conditionals and Loops: if/elif/else, for, while, break and continue
  • Looping Over Real Data in Python: Dicts, Lists of Dicts, enumerate and zip
  • Checking AI-Written Python Code: A Six-Step Habit That Finds Three Hidden Faults
  • Python Basics Practice: Report Card, Shopping Cart and Password Checker from a Prompt
  • Python Functions: Parameters, Return, Scope (LEGB), *args and **kwargs
  • Type Hints on Python Functions: Parameters, Returns, None and Collections
  • Python lambda, map, filter, Modules and Packages (with pip and venv)
  • Python Functions Practice: Bonus Calculator, Product Pipeline and a Math Package
  • Python Lists, Tuples, Sets and Dicts, Plus Type Hints on Variables
  • Python Comprehensions: List, Dict, Set and Generator Expressions, Read as Loops
  • Python Class Methods, Static Methods and Properties: What Each One Receives
  • Python Classes and Objects: __init__, self and PEP 8 Names
  • Python Inheritance and Polymorphism: super(), Overriding and Duck Typing
  • Python Multiple Inheritance, the MRO and Mixins
  • Python Encapsulation and Special Methods: Underscores, __str__, __add__ and __len__
  • Python Composition, Abstract Classes and Dataclasses
  • Python OOP Practice: Design a Bank, an Employee System and a Library
  • Set Up a Python AI Project with uv, VS Code and an API Key in .env
  • uv and pyproject.toml: Start, Add, Run and Rebuild a Python Project
  • Python try and except Basics: Catch an Error and Keep Going
  • Read and Write a File in Python: open, with, Modes and Encoding
  • Python Custom Exceptions and Advanced Error Handling: raise, raise from and the Call Stack
  • Python Logging and Debugging: Levels, Handlers, logger.exception and breakpoint()
  • Python File Modes, pathlib and Context Managers: x, r+, rb, Path and __enter__/__exit__
  • Python CSV, JSON and Large Files: csv, json, yield Pipelines, tomllib and pickle
  • Python Practice: Build a Log File Analyzer and a File Organizer
  • Python Project Structure for AI-Assisted Development: Packages, config.py and AGENTS.md
  • Regular Expressions in Python: search, findall, Groups and Greedy vs Lazy
  • Testing Python Code with pytest: assert, parametrize, fixtures and pytest.raises
  • Async Python: async def, await, asyncio.gather and the Blocking Trap
  • Django, FastAPI or Flask? The Same Blog Feature in Three Shapes, and How to Choose
  • One Blog, Three Frameworks: Routing, Models, Templates and Layout in Django, FastAPI and Flask
  • Getting Started with Flask: Routes, Jinja2 Templates and WSGI in One Small App
  • Your First Flask App with uv: From an Empty Folder to a Page in Debug Mode
  • Flask Routes, Templates and url_for: Converters, Forms, Redirects and the Signed Session
  • Flask-SQLAlchemy Models and Flask-Migrate: From a Python Class to a Real Table
  • Building a Blog with an AI Coding Agent: Plan Mode, a Master Prompt and the First Review
  • Handing a Figma Design to an AI Agent: Compare the Files, Then Review the Change
  • Inside a Flask Blog: The App Factory, Blueprints, the Instance Folder and CORS Done Right
  • How a Request and a Login Flow Through a Flask Blog: Flask-Login, CSRF and the Signed Session
  • Testing a Flask Blog with pytest: A Test App from the Factory, Fixtures and the Test Client
  1. Blog
  2. /
  3. Python
  4. /
  5. Modules, Files and Errors

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.

Chaand Sheikh

·27 November 2026·Updated 28 November 2026Modules, Files and Errors

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

The path of logger.info: the logger's level filter, then a LogRecord object, then a handler with its own level, its formatter turning the record into text, and finally the destination such as the console or a file logger.info() level filter LogRecord level, name, line Handler its own level Formatter record to text Destination console, app.log A message dropped at the first gate is never formatted.
Level filter, record, handler, formatter, destination.

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

  1. Read the traceback, starting from the last line. That's the reason.
  2. Add debug logs around the problem and turn them on.
  3. Pause the program at a breakpoint and look at the values.
  4. 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.

Tried the exercise? Share your answer or ask a question.

The StudyEasy AI Community is free to join, with the lesson files, notebooks and code.

Join free on Skool

Keep going in Python · 30 of 48

Previous
Python Custom Exceptions and Advanced Error Handling: raise, raise from and the Call Stack
Next post
Python File Modes, pathlib and Context Managers: x, r+, rb, Path and __enter__/__exit__

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.

On this page

  • The problem with print
  • Five levels, one gate
  • Moving the gate with basicConfig
  • What each line looks like
  • One message's path through logging
  • Handlers: short on the console, full in a file
  • Named loggers
  • Logging errors with logger.exception
  • Hunting a bug: four moves
  • breakpoint() and pdb
  • assert
  • The orders program, with logging
  • Try it yourself
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

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)

Single logo

Empowering Education, One Course at a Time

About
About usContact us
Legal
Terms of UsePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.