1. Home
  2. Blog
  3. Software Development

Software Development

Python Logging Explained: Levels, Handlers, Formatters and Mistakes to Avoid

print() is fine for a quick check, but real applications need logs with levels, timestamps and context that you can switch on and off. Here is how Python’s logging module works, including the quirks that confuse almost everyone, with every example run.

10 min read
Python logging explained: levels, handlers, formatters and mistakes to avoid

Key takeaways

  • Create one logger per module with logging.getLogger(__name__), and configure logging once at startup.
  • The default level is WARNING, so debug and info messages are hidden until you change it.
  • basicConfig() does nothing if logging is already set up, unless you pass force=True.
  • Pass values as arguments, log.info("id %s", x), so messages are only built when they will be shown.

A bug appears only in production, at 3 a.m., for one customer. The only evidence is whatever your application wrote down. Good logs turn that night into a ten-minute fix; print() statements scattered through the code usually do not.

We ran every example below with Python 3.13’s standard logging module. The outputs are from that run, with timestamps trimmed for readability.

Why not print()?

  • Levels: logging lets you keep debug messages in the code and switch them off in production.
  • Context: each record can include the time, module, level and line number automatically.
  • Destinations: the same message can go to the console, a file and a log service at once.
  • Control: libraries can log without forcing output on the applications that use them.

Log levels

Level Value Use for
DEBUG 10 Detailed information for diagnosing problems
INFO 20 Normal events: started, order created, job finished
WARNING 30 Something unexpected, but the program continues
ERROR 40 An operation failed
CRITICAL 50 The program may not be able to continue

A logger shows messages at its level and above. Out of the box, the root logger is set to WARNING, which surprises nearly every beginner:

logging.debug("debug hidden")
logging.info("info hidden")
logging.warning("warning shown")
# WARNING:root:warning shown

Only the warning appeared. Choose levels by who needs to act: if someone should be woken up, it is ERROR or CRITICAL; if it is useful only while investigating, it is DEBUG.

basicConfig and its quirk

logging.basicConfig() is the quickest way to set a level and format. But in our script, the earlier logging.warning() call had already configured the root logger behind the scenes, so this did nothing:

logging.basicConfig(level=logging.DEBUG, format="%(levelname)s %(message)s")
logging.debug("still hidden?")      # nothing printed

logging.basicConfig(level=logging.DEBUG, format="%(levelname)s %(message)s", force=True)
logging.debug("visible with force=True")
# DEBUG visible with force=True

basicConfig only acts if the root logger has no handlers yet. Calling any module-level function such as logging.warning() first, or importing a library that configures logging, means your settings are silently ignored. Call it once, at the very start of your program, or pass force=True (Python 3.8+) to replace the existing setup.

Named loggers

# in shop/orders.py
log = logging.getLogger(__name__)    # name: "shop.orders"

Loggers form a tree based on dotted names. shop.orders and shop.payments are children of shop, which is a child of the root logger. By default, a child passes its records up to its parents, which is called propagation. That is why configuring only the root logger at startup is enough for every module: their records all flow up to the root’s handlers. In our test, a record from shop.payments was printed by the root’s handler as ROOT shop.payments: payment ok.

Named loggers also let you tune noisy parts separately, for example logging.getLogger("urllib3").setLevel(logging.WARNING) to quieten a chatty library.

Handlers and formatters

A handler decides where records go; a formatter decides how they look.

h = logging.StreamHandler()
h.setFormatter(logging.Formatter(
    "%(asctime)s %(name)s %(levelname)s %(message)s",
    datefmt="%Y-%m-%dT%H:%M:%S"))

log = logging.getLogger("shop.orders")
log.addHandler(h)
log.setLevel(logging.INFO)

log.debug("not shown")
log.info("order %s created for %s", 101, "Asha")
log.warning("stock low: %d left", 2)

# 2026-11-08T17:40:18 shop.orders INFO order 101 created for Asha
# 2026-11-08T17:40:18 shop.orders WARNING stock low: 2 left

Common handlers include StreamHandler for the console, FileHandler, RotatingFileHandler and TimedRotatingFileHandler for files that should not grow forever, and SysLogHandler. Each handler can have its own level, so you can write everything to a file but only warnings to the console.

Logging exceptions

try:
    1 / 0
except ZeroDivisionError:
    log.exception("failed to compute tax")

# shop.orders ERROR failed to compute tax
# Traceback (most recent call last):
#   File "...logdemo.py", line 23, in <module>
#     1 / 0
# ZeroDivisionError: division by zero

log.exception() logs at ERROR level and attaches the full traceback automatically. Use it inside except blocks instead of log.error(str(e)), which throws away the most useful part. Our guide to Python exception handling shows where to catch and log errors.

Lazy formatting: why %s beats f-strings here

We logged an object whose __str__ counts how often it is called, at DEBUG level, on a logger set to WARNING:

quiet.debug("value %s", e)
print(Expensive.calls)    # 0

quiet.debug(f"value {e}")
print(Expensive.calls)    # 1

With the %s style, logging never built the message, because DEBUG was disabled. With the f-string, Python built the text before logging even saw it, and then threw it away. In a hot loop, or with expensive objects, that waste adds up. As our f-strings guide notes, logging is one of the few places where the older style is the better choice. Some linters, such as Ruff and Pylint, can flag f-strings in logging calls.

Duplicate log lines

The most common logging bug is every message appearing two or three times. We reproduced both causes:

for _ in range(3):
    dup.addHandler(logging.StreamHandler())
dup.warning("hello")
# lines written: 3

Adding a handler inside a function that runs more than once, such as a request handler or a test setup, stacks up handlers. The second cause is propagation: when we added a handler to shop.payments while the root logger also had one, the message twice? was written by both. Fix it by configuring handlers once, at startup, usually only on the root logger. If a child really needs its own handler, set propagate = False on it.

Tip: Libraries should never add handlers or call basicConfig. They should only create loggers and log. The application decides where logs go. The standard advice is for a library to attach a NullHandler to its top-level logger and leave everything else alone.

Structured JSON logs

Plain text is easy to read but hard to search across thousands of lines. Log platforms prefer one JSON object per line. A small custom formatter is enough to start:

class JsonFormatter(logging.Formatter):
    def format(self, r):
        d = {"level": r.levelname, "logger": r.name, "msg": r.getMessage()}
        d.update(getattr(r, "ctx", {}))
        return json.dumps(d)

jl.info("request done", extra={"ctx": {"path": "/orders", "status": 200, "ms": 42}})
# {"level": "INFO", "logger": "api", "msg": "request done", "path": "/orders", "status": 200, "ms": 42}

Fields like status and ms can now be filtered and charted directly. Libraries such as structlog and python-json-logger provide fuller versions. Structured logs are one of the three pillars discussed in our guide to monitoring vs observability.

Configuring an application

For anything beyond a script, keep logging setup in one place, using logging.config.dictConfig(). It accepts a dictionary, which you can load from a YAML or JSON file, describing formatters, handlers and logger levels. Set levels from an environment variable, such as LOG_LEVEL=DEBUG locally and INFO in production, so you can turn on detail without a code change. We did not run a full dictConfig setup for this article.

Best practices

  • Never log secrets such as passwords, tokens, card numbers or full personal data. Redact before logging.
  • Log events, not noise. One clear line per meaningful event beats ten vague ones.
  • Include identifiers such as order ID, user ID or request ID, so related lines can be found together.
  • Use UTC timestamps in ISO format in production, so logs from different servers line up.
  • Rotate or ship logs so files do not fill the disk.
  • Test important logs. pytest’s caplog fixture captures records, as shown in our pytest fixtures guide.

Testing your logs with caplog

Some log lines matter enough to test, such as the warning that an alert depends on. pytest’s built-in caplog fixture captures records during a test:

log = logging.getLogger("shop.orders")

def place_order(qty):
    if qty <= 0:
        log.warning("rejected order with qty=%s", qty)
        return False
    log.info("order placed qty=%s", qty)
    return True

def test_logs_warning(caplog):
    with caplog.at_level(logging.INFO, logger="shop.orders"):
        assert place_order(0) is False
    assert caplog.records[0].levelname == "WARNING"
    assert "qty=0" in caplog.text

# captured: [('WARNING', 'rejected order with qty=0')]

The test passed. Assert on the level and the important values rather than the full sentence, so rewording a message does not break the test. caplog.at_level() temporarily lowers the level for the duration of the block, which also makes DEBUG messages testable.

Final thoughts

Python’s logging module is powerful but has a few sharp edges: the WARNING default, basicConfig’s silent no-op, duplicate handlers and propagation. Use getLogger(__name__) in every module, configure handlers once at startup, use %s-style arguments and log.exception(), and move to JSON logs when you start searching them at scale.

Frequently asked questions

Why are my logging.debug messages not showing?

The default level is WARNING, so DEBUG and INFO are hidden. Set a lower level with basicConfig(level=logging.DEBUG) or logger.setLevel(), and check that basicConfig was not ignored.

Why does basicConfig not work?

It only configures the root logger if it has no handlers yet. If logging was already used or configured, the call does nothing. Call it first, or pass force=True.

Why do my log messages appear twice?

Usually a handler was added more than once, or both a child logger and the root logger have handlers and the record propagates to both. Configure handlers once at startup.

Should I use f-strings in logging calls?

Prefer logger.info(“value %s”, x). The message is built only if the level is enabled. In our test, the f-string version built the message even though it was discarded.

How do I log an exception with its traceback?

Call logger.exception(“message”) inside an except block. It logs at ERROR level and includes the full traceback.

Keep learning

Work with Stack Quora

Need help with testing, WordPress or SEO?

We help teams ship better software and grow their sites. Tell us what you are working on and we will suggest a clear next step.

Keep reading

More guides on testing, AI & modern development

Enjoyed this article? Pick a topic and jump straight into our newest tutorials.

Artificial Intelligence

LLM Structured Output Explained: Getting Reliable JSON From AI Models

LLM structured output explained with validation we ran in Pydantic: JSON mode and schemas, constrained decoding, the ways model output…

Read article →
DevOps

SSH Keys Explained: How They Work, ssh-keygen, Ed25519 and Safe Habits

SSH keys explained with keys we generated: public vs private keys, ssh-keygen, Ed25519 vs RSA, fingerprints, passphrases, ssh-agent, authorized_keys, config…

Read article →
DevOps

HTTP Caching Explained: Cache-Control, ETag and 304 Responses, With a Live Test

HTTP caching explained with a small server we ran: Cache-Control directives, max-age, no-cache vs no-store, ETag revalidation and 304 responses,…

Read article →
Test Automation

API Contract Testing Explained: Catch Breaking Changes Before They Ship

API contract testing explained with a schema check we ran: what a contract is, consumer-driven contracts, Pact, OpenAPI, which changes…

Read article →
Software Testing

Risk-Based Testing Explained: Score Risks, Build a Matrix and Test What Matters

Risk-based testing explained step by step: identifying risks, scoring likelihood and impact, building a risk matrix, mapping risk to test…

Read article →
Databases & SQL

SQL Constraints Explained: NOT NULL, UNIQUE, CHECK and FOREIGN KEY, Tested

SQL constraints explained with tests we ran: NOT NULL, UNIQUE, CHECK, DEFAULT, PRIMARY and FOREIGN KEY, the NULL loopholes, SQLite's…

Read article →
Databases & SQL

SQL Date Functions Explained: Adding, Comparing and Grouping Dates Without Bugs

SQL date functions explained with queries we ran: adding intervals, month-end surprises, date differences, the BETWEEN trap, grouping by day,…

Read article →
Software Development

Python asyncio Explained: async, await, gather and TaskGroup With Real Timings

Python asyncio explained with code we timed: coroutines, await, gather, TaskGroup, error handling, timeouts, limiting concurrency and the blocking-call mistake…

Read article →
Software Development

Debounce vs Throttle in JavaScript: How They Work, When to Use Each, Tested

Debounce vs throttle in JavaScript explained with timings we measured in Node.js: how each works, simple implementations, leading and trailing…

Read article →
Software Development

Python Context Managers Explained: The with Statement, contextlib and Real Uses

Python context managers explained with code we ran: how with works, __enter__ and __exit__, contextlib.contextmanager, suppress, ExitStack, database transactions and…

Read article →
Artificial Intelligence

LLM Temperature and Top-p Explained: How AI Models Choose Their Next Word

LLM temperature and top-p explained with a simulation we ran: how probabilities are reshaped, what top-p keeps, recommended settings by…

Read article →
DevOps

YAML Explained: Syntax, the Norway Problem and Other Traps We Tested

YAML explained with a parser test: basic syntax, lists and maps, the Norway problem, versions turning into floats, octal zip…

Read article →
DevOps

Cron Jobs Explained: Syntax, Real Schedules and the Mistakes That Break Them

Cron jobs explained with schedules we verified: the five fields, operators, real examples, the day-of-month OR day-of-week trap, environment problems,…

Read article →
Software Testing

Bug Life Cycle in Software Testing: Every Status, Who Owns It and Common Mistakes

The bug life cycle explained: every defect status from New to Closed, who owns each step, rejected, deferred and reopened…

Read article →
Test Automation

Property-Based Testing in Python: Hypothesis Finds the Bugs Your Examples Miss

Property-based testing explained with Hypothesis tests we ran: properties vs examples, strategies, shrinking, the real bugs it found in our…

Read article →
Databases & SQL

SQL Pagination Explained: OFFSET vs Keyset, With a Million-Row Test

SQL pagination explained with a million-row test we ran: LIMIT and OFFSET, why deep pages get slow, keyset (cursor) pagination,…

Read article →
Databases & SQL

SQL EXISTS vs IN: Differences, the NOT IN NULL Trap and Performance

SQL EXISTS vs IN explained with queries we ran: how each works, why NOT IN returns no rows when a…

Read article →
Software Development

Python Logging Explained: Levels, Handlers, Formatters and Mistakes to Avoid

Python logging explained with code we ran: levels, basicConfig quirks, named loggers, handlers and formatters, logger.exception, lazy formatting, duplicate logs…

Read article →
Software Development

JavaScript Map vs Object: Key Differences, Pitfalls and a Benchmark

JavaScript Map vs Object explained with code we ran in Node.js: key types, ordering, the prototype trap, JSON, size, WeakMap…

Read article →
Software Development

Python Type Hints Explained: Annotations, mypy and the Errors It Catches

Python type hints explained with a real mypy run: basic annotations, Optional and unions, TypedDict, Literal, Protocol, generics, Callable, strict…

Read article →
Artificial Intelligence

LLM Tokens Explained: How AI Models Read Text, Count Costs and Fill Context Windows

LLM tokens explained with a tokenizer we ran: how text is split, why counts differ by language and tokenizer, context…

Read article →
DevOps

Semantic Versioning Explained: MAJOR.MINOR.PATCH, Ranges and Release Rules

Semantic versioning explained with code we ran: MAJOR.MINOR.PATCH rules, pre-releases, correct version sorting, caret and tilde ranges, 0.x versions, lockfiles…

Read article →
DevOps

Git Reset vs Revert: How to Undo Commits Safely, With a Tested Example

Git reset vs revert explained with a repository we built: soft, mixed and hard reset, revert commits, reverting merges, recovering…

Read article →
Software Testing

The Test Pyramid Explained: Layers, Ratios and When to Break the Shape

The test pyramid explained: unit, integration and end-to-end layers, sensible ratios, the ice cream cone anti-pattern, the testing trophy and…

Read article →
Test Automation

pytest Fixtures Explained: Scope, yield Teardown, conftest.py and Factories

pytest fixtures explained with a suite we ran: how fixtures work, scopes, yield teardown, conftest.py, factory fixtures, parametrized fixtures, built-ins…

Read article →
Databases & SQL

SQL Upsert Explained: INSERT ON CONFLICT, MERGE and the REPLACE Trap

SQL upsert explained with queries we ran: INSERT ON CONFLICT DO UPDATE and DO NOTHING, the excluded row, conditional updates,…

Read article →
Databases & SQL

SQL LIKE Operator Explained: Wildcards, Case Sensitivity and Performance

The SQL LIKE operator explained with queries we ran: % and _ wildcards, escaping, NOT LIKE and NULL, case sensitivity…

Read article →
Artificial Intelligence

AI Hallucinations Explained: Why Language Models Make Things Up and How to Reduce It

AI hallucinations explained: what they are, why language models produce them, common types, how to reduce them with grounding and…

Read article →
Test Automation

Mocking in Python: unittest.mock, patch and the Mistakes That Make Tests Lie

Mocking in Python with unittest.mock, tested: Mock and return_value, side_effect, patching where a name is used, spec and autospec, mocking…

Read article →
Software Testing

Code Coverage Explained: Line vs Branch Coverage and What 100% Really Means

Code coverage explained with a real coverage.py run: line, branch and condition coverage, reading a report, why 100% coverage can…

Read article →
Artificial Intelligence

What Are AI Agents? How They Work, With a Simple Agent Loop You Can Run

What are AI agents? A plain guide to the agent loop, tools, memory and guardrails, with a small Python loop…

Read article →
Test Automation

TDD vs BDD: Key Differences, One Feature Built Both Ways and When to Use Each

TDD vs BDD explained with one discount feature built both ways: red-green-refactor with code we ran, Given-When-Then scenarios, tools, trade-offs…

Read article →
Software Testing

User Acceptance Testing (UAT): Process, Checklist and Real Examples

User acceptance testing explained: who runs it, how it differs from QA, a seven-step process, a UAT test case template,…

Read article →
Artificial Intelligence

What Are Embeddings? Vectors and Cosine Similarity Explained Simply

What are embeddings? A plain-language guide to vectors, cosine similarity and semantic search, with a small example we ran, common…

Read article →
Test Automation

Flaky Tests: What Causes Them and How to Fix Them for Good

Flaky tests explained with demos we ran: the main causes, how to confirm and diagnose one, proper fixes for timing,…

Read article →
Software Testing

Load Testing vs Stress Testing: Differences, Metrics and k6 Examples

Load testing vs stress testing explained: what each proves, spike and soak tests, the metrics that matter, why averages mislead,…

Read article →