Python logging best practices come down to a simple split: code everywhere creates named loggers and reports events, while one place at application start decides where those events go and how they look. Most logging problems in real projects, such as duplicate lines, missing tracebacks, silent libraries, or a log file that stops growing after logrotate runs, come from mixing those two jobs. This guide builds a complete standard-library setup that you can copy into a script, a Flask or FastAPI service or a worker: readable console output, JSON lines in a rotating file, a request ID on every record and non-blocking delivery for slow destinations. The standard-library examples were tested on Python 3.13, and all except the Python 3.12+ queue example also on Python 3.9.

From my own work: When I audit small Python services, the most common pattern is print() mixed with a few logging.info() calls on the root logger and a basicConfig() that never takes effect because an imported package configured logging first. Switching to module loggers and a single dictConfig usually fixes the missing output in one change.
The basics: one logger per module, lazy formatting
Create the logger at the top of every module with the module’s name. The dotted names form a hierarchy, so myapp.billing passes its records up to myapp and then to the root logger, and you can tune any branch later without touching the code:
import logging
log = logging.getLogger(__name__)
def charge(order_id, amount):
log.info("charging order %s amount %.2f", order_id, amount) # lazy formatting
try:
gateway_call(order_id, amount)
except TimeoutError:
log.exception("gateway timeout for order %s", order_id) # ERROR + traceback
raise
- Pass arguments instead of f-strings. With
log.debug("user %s", user)the string is only built if a handler will actually emit the record. An f-string is built every time, even when DEBUG is switched off. - Use
log.exception()insideexceptblocks. It logs at ERROR level and attaches the traceback.log.error(str(e))throws the stack away. - Never call
logging.info()directly in application modules. The module-level functions use the root logger, so you lose the name that tells you where a line came from.
The logging module documentation recommends exactly this getLogger(__name__) convention and explains how propagation passes records to ancestor loggers (Python docs: logging).
Log levels and when to use each one
Levels are just integers, and a record is processed only if its level is at or above both the logger’s level and the handler’s level. Keeping the meaning of each level consistent across a team makes alerts and searches far more useful:
| Level | Value | Use it for | Example |
|---|---|---|---|
| DEBUG | 10 | Detail you only need while diagnosing | SQL parameters, cache keys, payload sizes |
| INFO | 20 | Normal business events worth keeping | Order created, job finished in 4.2 s |
| WARNING | 30 | Something unexpected that the code handled | Retrying after a timeout, deprecated setting used |
| ERROR | 40 | An operation failed and someone may need to act | Payment failed, email could not be sent |
| CRITICAL | 50 | The application cannot continue | Database unreachable at startup |
WARNING is the default level of the root logger, which is why a fresh script shows warnings but not your INFO messages until logging is configured.
Configure Python logging once with dictConfig
logging.config.dictConfig() takes a plain dictionary, so the configuration can live in code, in a YAML or JSON file, or be adjusted from environment variables. The keys () for custom factories and ext://sys.stderr for external objects are part of the documented schema (Python docs: dictConfig schema). Save this as logsetup.py:
# logsetup.py - standard library only, Python 3.9+
import contextvars
import json
import logging
import logging.config
from datetime import datetime, timezone
request_id = contextvars.ContextVar("request_id", default="-")
class RequestIdFilter(logging.Filter):
"""Attach the current request id to every record."""
def filter(self, record):
record.request_id = request_id.get()
return True
class JsonFormatter(logging.Formatter):
"""One JSON object per line, ready for Loki, Elasticsearch or jq."""
STD = set(vars(logging.LogRecord("", 0, "", 0, "", (), None))) # built-in attributes
STD.update({"message", "asctime"})
def format(self, record):
out = {
"ts": datetime.fromtimestamp(record.created, timezone.utc).isoformat(timespec="milliseconds"),
"level": record.levelname,
"logger": record.name,
"msg": record.getMessage(),
}
# anything passed with extra={...} (and request_id from the filter)
out.update({k: v for k, v in vars(record).items() if k not in self.STD})
if record.exc_info:
out["exc"] = self.formatException(record.exc_info)
return json.dumps(out, default=str)
LOGGING = {
"version": 1,
"disable_existing_loggers": False,
"filters": {"request_id": {"()": RequestIdFilter}},
"formatters": {
"console": {"format": "%(asctime)s %(levelname)-8s %(name)s [%(request_id)s] %(message)s"},
"json": {"()": JsonFormatter},
},
"handlers": {
"console": {
"class": "logging.StreamHandler",
"stream": "ext://sys.stderr",
"formatter": "console",
"filters": ["request_id"],
"level": "INFO",
},
"file": {
"class": "logging.handlers.RotatingFileHandler",
"filename": "app.log",
"maxBytes": 10_000_000,
"backupCount": 5,
"encoding": "utf-8",
"formatter": "json",
"filters": ["request_id"],
"level": "DEBUG",
},
},
"loggers": {
"urllib3": {"level": "WARNING"}, # quiet a chatty dependency
},
"root": {"level": "DEBUG", "handlers": ["console", "file"]},
}
def setup_logging():
logging.config.dictConfig(LOGGING)
Three settings in that dictionary prevent the most common surprises:
disable_existing_loggers: False. The default isTrue, which disables every non-root logger that already exists when the configuration runs. Any module imported beforesetup_logging()would go silent (Python docs: disable_existing_loggers).- Handlers on the root logger only. Attach handlers in one place and let named loggers propagate. Adding the same handler to
myappand to root prints every line twice. - Levels on handlers, not only loggers. The root logger lets DEBUG through, the console shows INFO and above, and the file keeps everything for later diagnosis.
Now use it from the entry point of the application:
# app.py
import logging
from logsetup import setup_logging, request_id
log = logging.getLogger(__name__)
def handle(order_id, rid):
request_id.set(rid)
log.info("processing order %s", order_id, extra={"order_id": order_id})
try:
1 / 0
except ZeroDivisionError:
log.exception("order %s failed", order_id)
if __name__ == "__main__":
setup_logging()
log.debug("debug goes to the file only")
handle(1042, "req-7f3a")
logging.getLogger("urllib3").info("hidden: below WARNING")
Running python3 app.py prints readable lines with the traceback on stderr, while app.log receives one JSON object per line:
2026-11-28 10:16:42,735 INFO __main__ [req-7f3a] processing order 1042
2026-11-28 10:16:42,735 ERROR __main__ [req-7f3a] order 1042 failed
Traceback (most recent call last):
...
ZeroDivisionError: division by zero
$ head -2 app.log
{"ts": "2026-11-28T04:16:42.733+00:00", "level": "DEBUG", "logger": "__main__", "msg": "debug goes to the file only", "request_id": "-"}
{"ts": "2026-11-28T04:16:42.735+00:00", "level": "INFO", "logger": "__main__", "msg": "processing order 1042", "order_id": 1042, "request_id": "req-7f3a"}
Structured JSON logs and the extra argument
JSON lines are easy for machines and still readable with jq. Because the formatter copies every non-standard attribute of the record, anything passed through extra= becomes a field you can filter on, such as order_id above. A few rules keep structured logs useful:
- Keep the message constant and put variable data in fields:
log.info("payment failed", extra={"order_id": oid, "gateway": "stripe"})groups well in any log tool. - Do not use keys that clash with built-in record attributes such as
message,nameorargs; the logging module raisesKeyErrorwith the message Attempt to overwrite ‘name’ in LogRecord. - Never log secrets, passwords, full card numbers or session tokens. Redact in a filter if third-party code might log them. Keeping secrets out of code and logs in the first place is covered in .env files and secrets best practices.
- Use UTC timestamps with an offset, as the formatter does, so logs from several servers line up.
Filter the file with jq -c 'select(.level == "ERROR")' app.log when you need to.
Add a request ID with contextvars and a filter
A request ID ties together every line produced while handling one request, across modules. Storing it in a contextvars.ContextVar works for threads and for asyncio tasks, because each task gets its own copy of the context. The filter in logsetup.py copies the current value onto each record, and the formatter prints it. The cookbook shows the same filter technique for adding contextual information (Python Logging Cookbook).
In a web framework, set the variable in middleware. With FastAPI or Starlette, for example:
import uuid
from logsetup import request_id
@app.middleware("http")
async def add_request_id(request, call_next):
rid = request.headers.get("x-request-id") or uuid.uuid4().hex[:12]
token = request_id.set(rid)
try:
response = await call_next(request)
finally:
request_id.reset(token)
response.headers["x-request-id"] = rid
return response
Accepting an incoming X-Request-ID header lets you follow one request from Nginx through your app and into downstream services. For full distributed tracing across services, the same idea is formalised by trace and span IDs in OpenTelemetry, Prometheus and Grafana.
Log files: rotating, timed or watched handlers
A plain FileHandler grows forever. The standard library offers three better options, documented in the handlers reference (Python docs: logging.handlers):
| Handler | Rotates by | Use when |
|---|---|---|
RotatingFileHandler |
Size (maxBytes, backupCount) |
One process writes the file and Python owns rotation |
TimedRotatingFileHandler |
Time (when="midnight", backupCount) |
You want one file per day and Python owns rotation |
WatchedFileHandler |
Nothing; reopens the file if it is moved | logrotate or newsyslog rotates the file on Linux |
StreamHandler to stderr |
Not applicable | Docker or systemd collects output (journald, docker logs) |
Two warnings matter on servers. First, never let both Python and logrotate rotate the same file; pick one. With logrotate, use WatchedFileHandler so the process notices the rename and opens a new file instead of writing into the rotated one. The logrotate side of that setup is in logrotate for Nginx and PHP-FPM. Second, the cookbook states that logging to a single file from multiple processes is not supported (Python cookbook: multiple processes). Gunicorn or uWSGI workers that share a RotatingFileHandler can lose or interleave lines at rotation time. Log to stderr and let the process manager collect it, or send records through a queue to one writer.
On a VPS, stderr plus journald is often the simplest reliable choice: the unit file from systemd service hardening captures output automatically, and journalctl -u myapp -f follows it.
Non-blocking logging with QueueHandler and QueueListener
Handlers run in the thread that logs. A handler that sends email, posts to an HTTP endpoint or writes to a slow network disk adds its latency to every request. A QueueHandler only puts the record on a queue, and a QueueListener thread does the slow work:
# queue_demo.py - keep slow handlers off the request path
import logging
import logging.handlers
import queue
import time
class SlowHandler(logging.StreamHandler):
def emit(self, record):
time.sleep(0.05) # pretend this is a network log shipper
super().emit(record)
q = queue.SimpleQueue()
slow = SlowHandler()
slow.setFormatter(logging.Formatter("%(levelname)s %(message)s"))
listener = logging.handlers.QueueListener(q, slow, respect_handler_level=True)
root = logging.getLogger()
root.setLevel(logging.INFO)
root.addHandler(logging.handlers.QueueHandler(q))
listener.start()
t = time.perf_counter()
for i in range(20):
logging.info("event %d", i)
print(f"20 log calls took {(time.perf_counter() - t) * 1000:.1f} ms")
listener.stop() # flushes the queue before exit
On my machine the twenty calls returned in under a millisecond, although the handler needs a full second to write them. Always call listener.stop() at shutdown, for example with atexit, or the last records may never be written.
On Python 3.12 and newer, dictConfig can build the queue and listener for you; the handlers key lists the real handlers the listener should feed:
# Python 3.12+: let dictConfig build the queue and listener
import atexit
import logging
import logging.config
logging.config.dictConfig({
"version": 1,
"handlers": {
"stderr": {"class": "logging.StreamHandler", "stream": "ext://sys.stderr"},
"queue": {"class": "logging.handlers.QueueHandler", "handlers": ["stderr"], "respect_handler_level": True},
},
"root": {"level": "INFO", "handlers": ["queue"]},
})
qh = logging.getHandlerByName("queue")
qh.listener.start()
atexit.register(qh.listener.stop)
logging.getLogger("app").info("logged through the queue")
For heavy log volumes, shipping JSON lines to a central store is the next step; one way to do that on a single server is described in log ingestion with Vector, ClickHouse and Grafana.
Logging inside a library you publish
A library must never decide where logs go. It should create module loggers, log through them and do nothing else: no basicConfig(), no handlers on the root logger, no levels forced on the application. The Logging HOWTO recommends adding only a NullHandler to the library’s top-level logger, so nothing is printed unless the application configures logging (Python Logging HOWTO: libraries):
# mylib/__init__.py
import logging
logging.getLogger(__name__).addHandler(logging.NullHandler())
Applications can then turn your library up or down by name, for example "loggers": {"mylib": {"level": "DEBUG"}} in their dictConfig.
Common Python logging mistakes and fixes
basicConfig()does nothing. It is a no-op if the root logger already has handlers, which happens when an imported package configured logging. Passforce=True(Python 3.8+) or, better, use dictConfig.- Every line appears twice. A handler is attached to both a named logger and root, or
setup_logging()runs twice. Attach handlers once, on root. - No traceback in the log. Use
log.exception()orexc_info=True. - Logs vanish after logrotate. The process keeps writing to the renamed file. Use
WatchedFileHandlerorcopytruncate. - Debug logging slows production. Expensive arguments are computed anyway. Guard them with
if log.isEnabledFor(logging.DEBUG):.
Python logging best practices checklist
log = logging.getLogger(__name__)in every module; no directlogging.info()calls.- Lazy
%sarguments, constant messages, variable data inextra. log.exception()inexceptblocks, once per failure.- One
dictConfigcall at startup withdisable_existing_loggers: False. - Handlers on root only; levels set per handler and for noisy dependencies.
- JSON lines for machines, readable text for people, UTC timestamps.
- A request ID from
contextvarson every record. - Rotation owned by exactly one tool; stderr for Docker and systemd.
- QueueHandler for slow or network handlers; listener stopped at exit.
- Libraries add only a
NullHandler.
Want this done on your own server or site?
I am Saizul Amin, a web developer and technical SEO consultant. I set up and harden VPS servers, migrate WordPress sites, fix indexing problems and build automations. See my portfolio or get in touch.
FAQ
What are the most important Python logging best practices?
Use one logger per module with getLogger(__name__), pass arguments lazily instead of f-strings, use log.exception() in except blocks, configure logging once at startup with dictConfig, put handlers only on the root logger and never log secrets.
Should I use print or logging in Python?
Use logging for anything that runs unattended. Log records carry a level, a timestamp and the module name, can be filtered and routed without code changes, and can include tracebacks. print() is fine for the normal output of a command-line tool, not for diagnostics.
Why does logging.basicConfig not work?
basicConfig() only configures the root logger if it has no handlers yet. If an imported library or an earlier call already added one, your call is ignored. Use basicConfig(force=True) or configure everything with logging.config.dictConfig.
How do I write Python logs as JSON?
Write a small Formatter subclass that builds a dictionary from the log record, including fields passed through extra, and returns json.dumps() of it, then reference it in dictConfig with the () key. Third-party packages exist, but the standard library is enough.
Is Python logging thread-safe?
Yes. Handlers use locks, so many threads can log to the same handler in one process. Logging to the same file from several processes is not supported; use stderr with a process manager, a QueueHandler feeding one writer, or a socket or syslog handler.
Sources
- Python documentation: logging module
- Python documentation: logging.config and dictConfig
- Python documentation: logging.handlers
- Python Logging HOWTO
- Python Logging Cookbook

Saizul Amin is a web developer, AI automation engineer and technical SEO consultant from Dhaka, Bangladesh (B.Sc. in CSE, BUBT). Since 2017 he has worked in digital marketing, WordPress, IT infrastructure and server administration, including the bilingual SHR Bangladesh website for DGHS, WordPress sites for UK and US clients, and the ShobFree tools platform. He runs this blog on his own Ubuntu VPS with nginx, Redis and CloudPanel, and tests the guides here on it. Portfolio: saizul.com

