Skip to main content

Programming languages · Intermediate · 22 min

Log properly in Python with the logging module

By Padding · Updated 18 Nov 2026
Python 3.15.2 · python:3.15-slim (Debian)

You will replace the print calls in a small order-processing worker with Python's logging module, ending with a script that writes readable lines to the terminal and JSON lines to a file, tags every line with a job ID and keeps secrets out.

On this page

print is fine while you are poking at a script. It stops being fine once the script runs unattended: you cannot turn the noise down without editing code, every line looks the same whether it is a detail or a failure, there is no timestamp, and a log collector cannot tell one field from another.

Python's standard library has a full logging system in the logging module. In this tutorial you take a small worker that processes orders and is full of print calls, and move it to logging one piece at a time. You give each module its own logger, pick the right level for each message, configure everything once at the entry point with dictConfig, keep tracebacks with logger.exception, tag every line with the order being processed, and write JSON lines to a file that a log shipper can parse. You also stop a token from leaking into the log, and see why a library must never call logging.basicConfig.

Everything here uses the standard library only, so there is nothing to install beyond Python 3.15. The examples use python3; on Windows outside WSL, type py.

Step 1 · Start with a print-debugging worker

Create a throwaway project folder with a worker package and an entry script:

Bash
mkdir -p ~/logging-demo/worker
cd ~/logging-demo
touch worker/__init__.py

cat > worker/jobs.py <<'PY'
def charge(order):
    total = order["qty"] * order["price"]
    print("DEBUG total for", order["id"], "is", total)
    return total


def process_all(orders):
    print("starting", len(orders), "orders")
    done = 0
    for order in orders:
        if order["qty"] <= 0:
            print("WARNING skipping", order["id"])
            continue
        try:
            charge(order)
        except KeyError as err:
            print("ERROR", order["id"], "missing", err)
            continue
        print("charged", order["id"], "for", order["customer"])
        done += 1
    print("finished:", done, "of", len(orders))
    return done
PY

cat > run.py <<'PY'
from worker.jobs import process_all

ORDERS = [
    {"id": "A-101", "customer": "Àdìsá Bello", "qty": 2, "price": 1500.0},
    {"id": "A-102", "customer": "Wanjiru Kamau", "qty": 0, "price": 800.0},
    {"id": "A-103", "customer": "Thandiwe Dube", "qty": 1},
]

if __name__ == "__main__":
    process_all(ORDERS)
PY

python3 run.py

The three orders are chosen to hit every path: one is charged, one has a quantity of zero and is skipped, and one has no price, so charge raises KeyError.

Check it worked

The output is six lines: starting 3 orders, DEBUG total for A-101 is 3000.0, charged A-101 for Àdìsá Bello, WARNING skipping A-102, ERROR A-103 missing 'price' and finished: 1 of 3. The DEBUG, WARNING and ERROR words are only text. Nothing can filter on them.

Step 2 · Give the module a logger and pick levels

Each module asks for its own logger with logging.getLogger(__name__). __name__ is the module's dotted import path, here worker.jobs, so every line says where it came from and you can tune one part of the program without touching the rest. Loggers form a tree by those dots: worker.jobs is a child of worker, which is a child of the root logger.

Then each print becomes a call at a level that says how much the message matters:

  • debug: detail you want only while chasing a problem, such as computed values.
  • info: normal milestones, such as a batch starting and finishing.
  • warning: something unexpected that the program handled, such as skipping a bad order.
  • error: an operation failed.
  • critical: the program itself cannot carry on.

Rewrite worker/jobs.py:

Bash
cat > worker/jobs.py <<'PY'
import logging

log = logging.getLogger(__name__)


def charge(order):
    total = order["qty"] * order["price"]
    log.debug("order %s total %.2f", order["id"], total)
    return total


def process_all(orders):
    log.info("starting batch of %d orders", len(orders))
    done = 0
    for order in orders:
        if order["qty"] <= 0:
            log.warning("order %s skipped: quantity is %d", order["id"], order["qty"])
            continue
        try:
            charge(order)
        except KeyError as err:
            log.error("order %s failed: missing %s", order["id"], err)
            continue
        log.info("order %s charged for %s", order["id"], order["customer"])
        done += 1
    log.info("batch finished: %d of %d charged", done, len(orders))
    return done
PY

python3 run.py

The messages use %s and %d placeholders with the values passed as separate arguments. That is deliberate, and step 4 explains why.

Check it worked

Only two lines appear: order A-102 skipped: quantity is 0 and order A-103 failed: missing 'price'. Nothing has configured logging yet, so Python falls back to its handler of last resort, which prints warnings and worse to standard error, message only. The info and debug lines are dropped. This is the behaviour you want from a library: quiet until the application decides otherwise.

Step 3 · Configure logging once at the entry point

Configuration belongs in one place: the script that starts the program. Modules only ask for loggers and log. Create worker/logsetup.py with a configure function that uses logging.config.dictConfig, which takes the whole setup as one dictionary:

Bash
cat > worker/logsetup.py <<'PY'
import logging.config
import os


def configure():
    level = os.environ.get("LOG_LEVEL", "INFO").upper()
    logging.config.dictConfig({
        "version": 1,
        "disable_existing_loggers": False,
        "formatters": {
            "readable": {
                "format": "%(asctime)s %(levelname)-8s %(name)s: %(message)s",
                "datefmt": "%H:%M:%S",
            },
        },
        "handlers": {
            "console": {
                "class": "logging.StreamHandler",
                "formatter": "readable",
            },
        },
        "loggers": {
            "worker": {"level": level},
        },
        "root": {"level": "WARNING", "handlers": ["console"]},
    })
PY

cat > run.py <<'PY'
from worker.jobs import process_all
from worker.logsetup import configure

ORDERS = [
    {"id": "A-101", "customer": "Àdìsá Bello", "qty": 2, "price": 1500.0},
    {"id": "A-102", "customer": "Wanjiru Kamau", "qty": 0, "price": 800.0},
    {"id": "A-103", "customer": "Thandiwe Dube", "qty": 1},
]

if __name__ == "__main__":
    configure()
    process_all(ORDERS)
PY

python3 run.py

How the pieces fit:

  • A formatter decides what a line looks like. %(levelname)-8s pads the level to eight characters so messages line up.
  • A handler decides where lines go. StreamHandler writes to standard error by default.
  • The root logger holds the handler, so a record from any logger in the tree reaches it. Its level of WARNING keeps third-party libraries quiet.
  • The worker logger gets its level from the LOG_LEVEL environment variable, so you can turn detail up without editing code. worker.jobs has no level of its own and inherits it.
  • disable_existing_loggers defaults to True, which disables every logger that already exists when dictConfig runs, unless it is named in the config or is a child of a named one. Here worker.jobs survives because worker is named, but the loggers of any library imported earlier, and any of your own modules outside worker, would go silent. Setting it to False is the safe habit.

Check it worked

Five lines appear, something like:

Text
09:41:07 INFO     worker.jobs: starting batch of 3 orders
09:41:07 INFO     worker.jobs: order A-101 charged for Àdìsá Bello
09:41:07 WARNING  worker.jobs: order A-102 skipped: quantity is 0
09:41:07 ERROR    worker.jobs: order A-103 failed: missing 'price'
09:41:07 INFO     worker.jobs: batch finished: 1 of 3 charged

Now turn the detail up for one run:

Bash
LOG_LEVEL=DEBUG python3 run.py

A sixth line, DEBUG worker.jobs: order A-101 total 3000.00, appears after the first one.

Step 4 · Keep tracebacks and let logging format lazily

The error line says missing 'price' but not where it happened. Inside an except block, log.exception(...) logs at ERROR level and adds the full traceback. Change that one call by rewriting worker/jobs.py:

Bash
cat > worker/jobs.py <<'PY'
import logging

log = logging.getLogger(__name__)


def charge(order):
    total = order["qty"] * order["price"]
    log.debug("order %s total %.2f", order["id"], total)
    return total


def process_all(orders):
    log.info("starting batch of %d orders", len(orders))
    done = 0
    for order in orders:
        if order["qty"] <= 0:
            log.warning("order %s skipped: quantity is %d", order["id"], order["qty"])
            continue
        try:
            charge(order)
        except KeyError:
            log.exception("order %s failed", order["id"])
            continue
        log.info("order %s charged for %s", order["id"], order["customer"])
        done += 1
    log.info("batch finished: %d of %d charged", done, len(orders))
    return done
PY

python3 run.py

Use log.exception only inside an except block. Elsewhere, pass exc_info=True to any level, for example log.warning("retrying", exc_info=True).

Now the placeholders. When you write log.debug("state: %s", value), logging checks the level first and only builds the string if the line will be written. An f-string is built before the call, every time, even when debug is off. Write a small script that counts how often a value is turned into text:

Bash
cat > lazy.py <<'PY'
import logging

logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s")
log = logging.getLogger("lazy")


class Snapshot:
    renders = 0

    def __str__(self):
        Snapshot.renders += 1
        return "<large snapshot>"


snap = Snapshot()
log.debug("state: %s", snap)
print("after the %-style call:", Snapshot.renders)
log.debug(f"state: {snap}")
print("after the f-string call:", Snapshot.renders)

if log.isEnabledFor(logging.DEBUG):
    log.debug("sum: %d", sum(range(50_000_000)))
PY

python3 lazy.py

lazy.py is a standalone script, its own entry point, so calling basicConfig there is fine. The last two lines show the guard for work that is expensive to compute, not only to format: isEnabledFor skips the sum entirely at INFO. The Ruff linter flags f-strings in logging calls with rule G004, if you want the habit enforced.

Check it worked

python3 run.py now prints Traceback (most recent call last): under the ERROR line, ending with KeyError: 'price'. python3 lazy.py prints after the %-style call: 0 and then after the f-string call: 1: the debug line was never written, but the f-string still did the work.

Step 5 · Tag every line with the job ID

When orders are processed in parallel, or the log mixes many runs, each line needs to say which order it belongs to. Repeating the ID in every message is easy to forget. Instead, hold the current ID in a ContextVar and copy it onto every record with a filter. The same pattern carries a request ID through a web app.

Create worker/logtools.py:

Bash
cat > worker/logtools.py <<'PY'
import logging
from contextvars import ContextVar

job_id = ContextVar("job_id", default="-")


class JobIdFilter(logging.Filter):
    """Copy the current job ID onto every record that reaches a handler."""

    def filter(self, record):
        record.job_id = job_id.get()
        return True
PY

Rewrite worker/jobs.py so it sets the ID for each order and resets it afterwards. The messages no longer repeat the ID, because the tag carries it:

Bash
cat > worker/jobs.py <<'PY'
import logging

from worker.logtools import job_id

log = logging.getLogger(__name__)


def charge(order):
    total = order["qty"] * order["price"]
    log.debug("total %.2f", total)
    return total


def process_one(order):
    if order["qty"] <= 0:
        log.warning("skipped: quantity is %d", order["qty"])
        return False
    try:
        charge(order)
    except KeyError:
        log.exception("charge failed")
        return False
    log.info("charged for %s", order["customer"])
    return True


def process_all(orders):
    log.info("starting batch of %d orders", len(orders))
    done = 0
    for order in orders:
        ctx = job_id.set(order["id"])
        try:
            done += process_one(order)
        finally:
            job_id.reset(ctx)
    log.info("batch finished: %d of %d charged", done, len(orders))
    return done
PY

Register the filter in worker/logsetup.py, attach it to the handler and add [%(job_id)s] to the format:

Bash
cat > worker/logsetup.py <<'PY'
import logging.config
import os


def configure():
    level = os.environ.get("LOG_LEVEL", "INFO").upper()
    logging.config.dictConfig({
        "version": 1,
        "disable_existing_loggers": False,
        "filters": {
            "job_id": {"()": "worker.logtools.JobIdFilter"},
        },
        "formatters": {
            "readable": {
                "format": "%(asctime)s %(levelname)-8s %(name)s [%(job_id)s] %(message)s",
                "datefmt": "%H:%M:%S",
            },
        },
        "handlers": {
            "console": {
                "class": "logging.StreamHandler",
                "formatter": "readable",
                "filters": ["job_id"],
            },
        },
        "loggers": {
            "worker": {"level": level},
        },
        "root": {"level": "WARNING", "handlers": ["console"]},
    })
PY

python3 run.py

The "()" key tells dictConfig to build the filter by calling the class named in the string. The filter goes on the handler, not on a logger, for two reasons. A filter on a logger only sees records logged on that exact logger, not ones passed up from its children. And every record that reaches the handler, including ones from third-party libraries, needs a job_id attribute, or the format string fails with a --- Logging error --- report.

The other tool for this is logging.LoggerAdapter, which wraps one logger and adds fixed extra fields to every call made through it:

Bash
cat > adapter_demo.py <<'PY'
import logging

logging.basicConfig(level=logging.INFO, format="%(levelname)s [%(job_id)s] %(message)s")
base = logging.getLogger("adapter-demo")

for order_id in ("A-101", "A-102"):
    log = logging.LoggerAdapter(base, {"job_id": order_id})
    log.info("picked up")
PY

python3 adapter_demo.py

It prints INFO [A-101] picked up and INFO [A-102] picked up. An adapter only tags calls made through that adapter object, so functions in other modules that use their own logger miss out. The context variable reaches every module, which is why the worker uses it.

Check it worked

Each worker line now carries a tag: [-] on the batch start and finish lines, [A-101] on the charge, [A-102] on the skip and [A-103] on the failure line, with its traceback below it.

Step 6 · Write JSON lines to a file

People read the terminal; log shippers and search tools read files. They cope best with one JSON object per line, because each field arrives already named and a multi-line traceback stays inside one record. Add a small formatter to worker/logtools.py by rewriting it:

Bash
cat > worker/logtools.py <<'PY'
import json
import logging
from contextvars import ContextVar
from datetime import datetime, timezone

job_id = ContextVar("job_id", default="-")


class JobIdFilter(logging.Filter):
    """Copy the current job ID onto every record that reaches a handler."""

    def filter(self, record):
        record.job_id = job_id.get()
        return True


class JsonFormatter(logging.Formatter):
    """Format each record as one line of JSON."""

    def format(self, record):
        entry = {
            "time": datetime.fromtimestamp(record.created, timezone.utc).isoformat(timespec="milliseconds"),
            "level": record.levelname,
            "logger": record.name,
            "job_id": getattr(record, "job_id", "-"),
            "message": record.getMessage(),
        }
        if record.exc_info:
            entry["exception"] = self.formatException(record.exc_info)
        return json.dumps(entry, ensure_ascii=False)
PY

record.getMessage() fills in the %s placeholders. Times are in UTC with milliseconds, so lines from servers in different time zones sort correctly. ensure_ascii=False keeps names such as Àdìsá readable instead of turning them into \u escapes, which matters for logs that hold Yoruba, Amharic or any other text outside plain English.

Now add a second handler in worker/logsetup.py. The console stays at INFO; the file takes DEBUG too, so the detail is there when you need it without cluttering the terminal:

Bash
cat > worker/logsetup.py <<'PY'
import logging.config
import os


def configure(log_file="worker.jsonl"):
    level = os.environ.get("LOG_LEVEL", "INFO").upper()
    logging.config.dictConfig({
        "version": 1,
        "disable_existing_loggers": False,
        "filters": {
            "job_id": {"()": "worker.logtools.JobIdFilter"},
        },
        "formatters": {
            "readable": {
                "format": "%(asctime)s %(levelname)-8s %(name)s [%(job_id)s] %(message)s",
                "datefmt": "%H:%M:%S",
            },
            "json": {"()": "worker.logtools.JsonFormatter"},
        },
        "handlers": {
            "console": {
                "class": "logging.StreamHandler",
                "level": "INFO",
                "formatter": "readable",
                "filters": ["job_id"],
            },
            "file": {
                "class": "logging.FileHandler",
                "filename": log_file,
                "encoding": "utf-8",
                "level": "DEBUG",
                "formatter": "json",
                "filters": ["job_id"],
            },
        },
        "loggers": {
            "worker": {"level": level},
        },
        "root": {"level": "WARNING", "handlers": ["console", "file"]},
    })
PY

rm -f worker.jsonl
LOG_LEVEL=DEBUG python3 run.py

FileHandler appends, so the rm gives you a clean file to inspect. Passing encoding makes the file UTF-8 whatever the system locale is. A plain FileHandler also grows forever. On a small server with little disk, use logging.handlers.RotatingFileHandler with maxBytes and backupCount instead, and keep production at INFO: if your logs travel over a metered or prepaid connection to a collector, every debug line costs data.

Check it worked

The terminal shows the same five readable lines as before, with no debug line. Read the file back as JSON:

Bash
python3 - <<'PY'
import json

with open("worker.jsonl", encoding="utf-8") as f:
    entries = [json.loads(line) for line in f]
for e in entries:
    print(e["level"], e["job_id"], e["message"], "+traceback" if "exception" in e else "")
print(len(entries), "lines parsed")
PY

Every line parses. There are six entries, including DEBUG A-101 total 3000.00, INFO A-101 charged for Àdìsá Bello and ERROR A-103 charge failed +traceback, and the last line is 6 lines parsed.

Step 7 · Keep secrets out of the logs

Logs get copied to collectors, pasted into chats and kept for months, so a token written to a log is a leaked token. The first rule is to never log whole headers, request bodies, config objects or environment dictionaries. Log the few fields you need.

To see why a safety net is still worth having, add a module with exactly that mistake. It reads a payment API token from the WORKER_API_TOKEN environment variable, which is the right place for it, then logs the headers it builds:

Bash
cat > worker/payments.py <<'PY'
import logging
import os

log = logging.getLogger(__name__)


def build_headers():
    token = os.environ["WORKER_API_TOKEN"]
    headers = {"Authorization": f"Bearer {token}"}
    log.debug("payment headers: %s", headers)  # the mistake: this logs the token
    return headers
PY

cat > leak.py <<'PY'
from worker.logsetup import configure
from worker.payments import build_headers

configure()
build_headers()
PY

Set the variable to a made-up value without it landing in your shell history. read -s hides what you type; enter any long random string, not a real credential:

Bash
read -rsp "Made-up token: " WORKER_API_TOKEN && export WORKER_API_TOKEN

Run it at debug level and look for the token in the file:

Bash
rm -f worker.jsonl
LOG_LEVEL=DEBUG python3 leak.py
grep -cF "$WORKER_API_TOKEN" worker.jsonl

grep prints 1: the token is in the log. Now add a filter that replaces known secret values before any handler writes the line. Create worker/redact.py:

Bash
cat > worker/redact.py <<'PY'
import logging
import os


class RedactFilter(logging.Filter):
    """Replace the values of the named environment variables with [redacted]."""

    def __init__(self, env_vars=()):
        super().__init__()
        self.secrets = [os.environ[name] for name in env_vars if os.environ.get(name)]

    def filter(self, record):
        if self.secrets:
            message = record.getMessage()
            for secret in self.secrets:
                message = message.replace(secret, "[redacted]")
            record.msg, record.args = message, None
        return True
PY

Register it in worker/logsetup.py and put it on both handlers. Keys other than "()" are passed to the class as keyword arguments, so env_vars arrives in __init__:

Bash
cat > worker/logsetup.py <<'PY'
import logging.config
import os


def configure(log_file="worker.jsonl"):
    level = os.environ.get("LOG_LEVEL", "INFO").upper()
    logging.config.dictConfig({
        "version": 1,
        "disable_existing_loggers": False,
        "filters": {
            "job_id": {"()": "worker.logtools.JobIdFilter"},
            "redact": {"()": "worker.redact.RedactFilter", "env_vars": ["WORKER_API_TOKEN"]},
        },
        "formatters": {
            "readable": {
                "format": "%(asctime)s %(levelname)-8s %(name)s [%(job_id)s] %(message)s",
                "datefmt": "%H:%M:%S",
            },
            "json": {"()": "worker.logtools.JsonFormatter"},
        },
        "handlers": {
            "console": {
                "class": "logging.StreamHandler",
                "level": "INFO",
                "formatter": "readable",
                "filters": ["redact", "job_id"],
            },
            "file": {
                "class": "logging.FileHandler",
                "filename": log_file,
                "encoding": "utf-8",
                "level": "DEBUG",
                "formatter": "json",
                "filters": ["redact", "job_id"],
            },
        },
        "loggers": {
            "worker": {"level": level},
        },
        "root": {"level": "WARNING", "handlers": ["console", "file"]},
    })
PY

rm -f worker.jsonl
LOG_LEVEL=DEBUG python3 leak.py
grep -F "$WORKER_API_TOKEN" worker.jsonl || echo "token not found in the log"

The filter covers messages only, not traceback text, and only the secrets you name. It is a net for mistakes, not the fix: in your own code, delete lines like the one in payments.py.

Check it worked

The last command prints token not found in the log. Open worker.jsonl and the message reads payment headers: {'Authorization': 'Bearer [redacted]'}.

Step 8 · See why libraries must not call basicConfig

logging.basicConfig attaches a handler to the root logger, but only if the root logger has none yet. Otherwise it does nothing, without a warning. A library that calls it at import time takes that decision away from the application. Make a tiny example of the mistake in its own folder:

Bash
mkdir -p ~/logging-demo/libdemo
cd ~/logging-demo/libdemo

cat > chatty.py <<'PY'
import logging

logging.basicConfig(level=logging.DEBUG, format="chatty: %(message)s")  # wrong in a library
log = logging.getLogger(__name__)


def fetch():
    log.debug("fetching")
PY

cat > app.py <<'PY'
import logging

import chatty

logging.basicConfig(level=logging.WARNING, format="%(levelname)s app: %(message)s")
logging.getLogger("app").warning("disk almost full")
chatty.fetch()
PY

python3 app.py

The output is chatty: disk almost full and chatty: fetching. The application asked for WARNING and its own format, and got neither, because the library's import ran first. (basicConfig(force=True) overrides it, but the application should not have to know.)

The library-friendly version only creates a logger and adds a NullHandler, which discards records unless the application configures logging. That also stops the handler of last resort from printing the library's warnings when nobody asked:

Bash
cat > chatty.py <<'PY'
import logging

log = logging.getLogger(__name__)
log.addHandler(logging.NullHandler())


def fetch():
    log.debug("fetching")
PY

python3 app.py
cd ~/logging-demo

If you ever turn the worker package into a library, the same applies: the two lines at the top of chatty.py go in its __init__.py, and logsetup.py stays with the application.

Check it worked

The second run prints one line, WARNING app: disk almost full. The library's debug line is gone and the application's format is back.

Step 9 · Clean up

Remove the demo folder and the made-up token. Python stays installed:

Bash
cd ~
rm -rf ~/logging-demo
unset WORKER_API_TOKEN

Check it worked

ls ~/logging-demo reports that there is no such file or directory, and echo "${WORKER_API_TOKEN:-unset}" prints unset.

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.