Production Python: Logging, Config, CLIs and Packaging
After this lesson, you will be able to:
- Replace print with the logging module, using levels and JSON log lines written to stdout
- Load configuration into a typed, validated object that fails at startup with every problem listed
- Build a command-line interface with argparse whose main function takes an argv list and returns an exit code
- Describe a small library's pyproject.toml, src layout and entry point, and check them by running code
- Wrap a flaky call in a retry decorator with exponential backoff and jitter
- Apply a short checklist to decide whether a script is ready to run unattended
Before you start
#What Breaks When a Script Becomes a Service
When you run a script yourself, you are part of the system. You watch the output, you read the traceback, you edit a constant at the top and run it again. Once the script runs on a schedule or inside a container, you are gone, and four things you were doing silently have to be done by the code.
| Question | You at a terminal | Nobody watching |
|---|---|---|
| What happened? | You read the screen | Only what the code wrote down |
| Where am I running? | Paths and keys typed into the file | Settings come from the environment |
| How do I start you? | python script.py and edit constants | A scheduler runs a command and reads the exit code |
| How does my code get here? | It is already on your disk | It must install on a machine you have never seen |
Here is the kind of script that works for months and then fails. A few rows have a bad value, and the loop prints as it goes.
rows = [{"id": "r1", "x": "0.8"}, {"id": "r2", "x": "n/a"}, {"id": "r3", "x": "0.3"}]
print("scoring...")
try:
for row in rows:
print("row", row["id"], float(row["x"]) * 2)
except ValueError as err:
print("crashed:", err)Output:
scoring...
row r1 1.6
crashed: could not convert string to float: 'n/a'
try, this would end in a traceback. Either way the message does not say which row failed, has no time or severity, and row r3 never ran, so one bad value cost you the whole batch. The next four sections fix each part of that, in order: logging, configuration, a command line, and packaging.#Logging Instead of print
logging module gives every message a level, a name for where it came from, and a destination you control. You will not need to delete anything when you ship, because the level decides what appears.There are five levels. A logger set to a level shows messages at that level and above, and drops the rest.
| Level | Number | Use it for |
|---|---|---|
DEBUG | 10 | Detail you want while developing |
INFO | 20 | Normal progress: "loaded model", "scored row" |
WARNING | 30 | Something odd that the program survived |
ERROR | 40 | An operation failed |
CRITICAL | 50 | The program cannot continue |
configure_logging once, and that is the only place that decides where records go.import logging
import sys
def configure_logging(level: int = logging.INFO) -> None:
"""Call once, from the program's entry point. Libraries never call this."""
handler = logging.StreamHandler(sys.stdout)
handler.setFormatter(logging.Formatter("%(levelname)-8s %(name)s: %(message)s"))
# force=True replaces any earlier handlers, so a second call cannot stack them
logging.basicConfig(level=level, handlers=[handler], force=True)
log = logging.getLogger("scoring") # in a real module: logging.getLogger(__name__)
def score_rows(rows):
for row in rows:
try:
score = float(row["x"]) * 2
except ValueError:
log.warning("skipping row %s: bad x=%r", row["id"], row["x"])
continue
log.info("scored row %s -> %.2f", row["id"], score)
log.debug("this line is below INFO and is dropped")
rows = [{"id": "r1", "x": "0.8"}, {"id": "r2", "x": "n/a"}, {"id": "r3", "x": "0.3"}]
configure_logging() # the entry point does this once
score_rows(rows)Output:
INFO scoring: scored row r1 -> 1.60
WARNING scoring: skipping row r2: bad x='n/a'
INFO scoring: scored row r3 -> 0.60
StreamHandler(sys.stdout) sends it to standard output, which is where Docker and most schedulers collect a program's logs. A formatter decides what the line looks like. The handler sits on the root logger, and every named logger passes its records up to it.logging.getLogger(__name__) in real code. Names are dotted, so myapp.data.loader sits under myapp.data, and you can raise or lower the level for a whole package at once. The rule that keeps this tidy: only the entry point configures logging, and every other module just asks for a logger. A library that adds its own handlers fights with the application, as the exercise below shows.A logger is set to WARNING and has one stdout handler. You run: log.debug("a") log.info("b") log.warning("c") log.error("d") What appears?
#Pass values as arguments, not f-strings
log.warning("skipping row %s", row_id) and did not build the string first. The logger formats the message only if it will be emitted, so a dropped DEBUG call costs almost nothing. An f-string is built before the call, whether or not the line is ever shown, which matters for a large array or a slow __str__ inside a loop.#JSON log lines
WARNING scoring: skipping row r2. A log search tool wants fields it can filter on, such as row_id. The usual answer is one JSON object per line. The standard library has no JSON formatter, but a small one is enough:import json
import logging
import sys
# Attributes every LogRecord already has; anything else came from extra
STANDARD = set(vars(logging.makeLogRecord({}))) | {"message", "asctime"}
class JsonFormatter(logging.Formatter):
def format(self, record: logging.LogRecord) -> str:
data = {
"time": self.formatTime(record, "%Y-%m-%dT%H:%M:%S"),
"level": record.levelname,
"logger": record.name,
"message": record.getMessage(),
}
for key, value in vars(record).items():
if key not in STANDARD:
data[key] = value
if record.exc_info:
data["exception"] = self.formatException(record.exc_info).splitlines()[-1]
return json.dumps(data, default=str) # default=str keeps an odd value from crashing the logger
handler = logging.StreamHandler(sys.stdout)
handler.setFormatter(JsonFormatter())
logging.basicConfig(level=logging.INFO, handlers=[handler], force=True) # entry point, once
logger = logging.getLogger("service")
logger.info("scored", extra={"row_id": "r1", "score": 1.6})
try:
float("n/a")
except ValueError:
logger.exception("row failed", extra={"row_id": "r2"})Output:
{"time": "2026-10-04T22:51:45", "level": "INFO", "logger": "service", "message": "scored", "row_id": "r1", "score": 1.6}
{"time": "2026-10-04T22:51:45", "level": "ERROR", "logger": "service", "message": "row failed", "row_id": "r2", "exception": "ValueError: could not convert string to float: 'n/a'"}
time will differ. extra={...} copies each key onto the record as an attribute. The loop over vars(record) is what writes them into the JSON line. logger.exception is logger.error plus the active exception, and only works inside an except block.The same call, logger.info("scored", extra={"row_id": "r1"}), goes to a logger whose handler uses logging.Formatter("%(message)s"). What is printed?
extra key may not collide with a record attribute: extra={"name": "x"} raises KeyError: "Attempt to overwrite 'name' in LogRecord", so pick names like row_id. And never log a secret or a whole config object that contains one.A helper called setup() adds a handler to the trainer logger, and two modules both call it, so every message prints twice. (The better design is one call from the entry point, but a helper that can be called twice must still be safe.) Fix setup() so that calling it any number of times leaves one handler.
epoch 1 done
#Configuration as a Typed Object
.env files, os.environ, and keeping secrets out of git is the job of Environment Variables and Secrets, so this section only covers what to do after you read them.The trap is that every environment variable is a string. This is the classic result:
print(bool("false"), bool("0"), bool(""))Output:
True True False
DEBUG=false read with bool(os.environ["DEBUG"]) turns debugging on. The fix is to parse each setting once, in one place, into the type you want, and to stop the program at startup if anything is wrong. A frozen dataclass does that without any library.import os
from collections.abc import Mapping
from dataclasses import dataclass, field
TRUE_WORDS = {"1", "true", "yes", "on"}
FALSE_WORDS = {"0", "false", "no", "off", ""}
@dataclass(frozen=True)
class Config:
model_path: str
batch_size: int
debug: bool
api_key: str = field(repr=False) # repr=False keeps it out of print() and logs
def parse_bool(name: str, raw: str) -> bool:
word = raw.strip().lower()
if word in TRUE_WORDS:
return True
if word in FALSE_WORDS:
return False
raise ValueError(f"{name} must be true or false, got {raw!r}")
def load_config(env: Mapping[str, str] = os.environ) -> Config:
"""Read every setting once, at startup, and report all problems together."""
errors = []
if not env.get("API_KEY"):
errors.append("API_KEY is required")
try:
batch_size = int(env.get("BATCH_SIZE", "32"))
if not 1 <= batch_size <= 1024:
errors.append(f"BATCH_SIZE must be 1 to 1024, got {batch_size}")
except ValueError:
errors.append(f"BATCH_SIZE must be a whole number, got {env['BATCH_SIZE']!r}")
batch_size = 0
try:
debug = parse_bool("DEBUG", env.get("DEBUG", "false"))
except ValueError as err:
errors.append(str(err))
debug = False
if errors:
raise ValueError("bad configuration: " + "; ".join(errors))
return Config(
model_path=env.get("MODEL_PATH", "models/classifier.pkl"),
batch_size=batch_size,
debug=debug,
api_key=env["API_KEY"],
)
good = {"API_KEY": "sk-demo-123", "BATCH_SIZE": "64", "DEBUG": "false"}
print(load_config(good))
try:
load_config({"BATCH_SIZE": "lots", "DEBUG": "maybe"})
except ValueError as err:
print(err)Output:
Config(model_path='models/classifier.pkl', batch_size=64, debug=False)
bad configuration: API_KEY is required; BATCH_SIZE must be a whole number, got 'lots'; DEBUG must be true or false, got 'maybe'
os.environ, so a test passes a plain dict and never touches the real environment. It collects every error instead of stopping at the first, so the person fixing the deployment makes one trip. And frozen=True means that later code cannot quietly change batch_size: assigning to it raises FrozenInstanceError.A teammate moves the hardcoded API key into a .env file and commits everything, including the .env. What has this fixed?
pydantic-settings does the same job from a class with type hints. It is not available in the browser, so this one is a terminal transcript. It was run on Python 3.12 with pydantic-settings 2.15.0, with the three variables set as the first lines show:# Needs `pip install pydantic-settings`, which is not available in the browser.
import os
from pydantic_settings import BaseSettings
# Set here only for the demo; a real job gets these from its environment
os.environ.update(API_KEY="sk-demo-123", BATCH_SIZE="64", DEBUG="false")
class Settings(BaseSettings):
api_key: str
batch_size: int = 32
debug: bool = False
print(Settings()) # reads API_KEY, BATCH_SIZE and DEBUG from the environmentapi_key='sk-demo-123' batch_size=64 debug=False
BATCH_SIZE=lots, DEBUG=maybe and no API_KEY, Settings() raises one error listing all three problems (long tails and link lines shortened to ...):3 validation errors for Settings
api_key
Field required [type=missing, ...]
batch_size
Input should be a valid integer, unable to parse string as an integer [type=int_parsing, ...]
debug
Input should be a valid boolean, unable to interpret input [type=bool_parsing, ...]
api_key: SecretStr and print shows SecretStr('**********'), while .get_secret_value() returns the text. The idea is the same as the dataclass above: parse once, at startup, into typed fields.#A Command-Line Interface with argparse
argparse, and it gives you three things for free: type conversion, a generated --help, and an error message when the arguments are wrong.import argparse
def build_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(prog="train", description="Train a classifier.")
parser.add_argument("data", help="path to the training CSV")
parser.add_argument("--epochs", type=int, default=10)
parser.add_argument("--lr", type=float, default=0.001)
parser.add_argument("--model", choices=["linear", "tree"], default="linear")
parser.add_argument("-v", "--verbose", action="store_true")
return parser
def main(argv: list[str] | None = None) -> int:
args = build_parser().parse_args(argv)
print(args)
return 0
print(main(["data/train.csv", "--epochs", "3", "-v"]))Output:
Namespace(data='data/train.csv', epochs=3, lr=0.001, model='linear', verbose=True)
0
main takes an argv list. When it is None, parse_args reads the real command line, so the script runs normally, and a test can call main([...]) directly. Second, main returns an integer. Put this at the bottom of the file and the return value becomes the process exit code:# The bottom of train.py: the exit code is how a scheduler learns whether the run worked.
if __name__ == "__main__":
raise SystemExit(main())By convention, 0 means success and anything else means failure, and most schedulers and CI systems act on that. A script that prints "failed" and exits 0 looks like a success to them.
argparse prints a usage message to stderr and exits with code 2. You can see this by catching SystemExit:import argparse
parser = argparse.ArgumentParser(prog="train")
parser.add_argument("--epochs", type=int, default=10)
parser.add_argument("--model", choices=["linear", "tree"], default="linear")
for bad in (["--epochs", "ten"], ["--model", "svm"]):
try:
parser.parse_args(bad)
except SystemExit as exit_:
print("exit code", exit_.code)Output:
exit code 2
exit code 2
invalid int value: 'ten', invalid choice: 'svm') go to stderr, so a console shows them above the exit codes. Third-party libraries offer a shorter syntax. Typer, for example, builds a command line from a function's type hints. argparse ships with Python and covers what you need until you want subcommands and nicer help.#Packaging a Small Library
.py files between machines does not scale. A package declares its name, version, dependencies and commands in one file, pyproject.toml, and a build tool turns it into something pip or uv can install anywhere. Modules, Packages and pip showed how to import; this section is about making your own code installable.A small library with a command-line entry point looks like this:
mlkit/
pyproject.toml
src/
mlkit/
__init__.py
cli.py
tests/
test_cli.py
src/ is called the src layout. It stops your tests from importing the source folder by accident. Until you install the package, import mlkit fails, so a test that passes proves the installed version works.# @read-only
# pyproject.toml, shown here for reading
[build-system]
requires = ["setuptools>=68"]
build-backend = "setuptools.build_meta"
[project]
name = "mlkit"
version = "0.1.0"
description = "Small helpers for scoring rows"
requires-python = ">=3.10"
dependencies = []
[project.scripts]
mlkit = "mlkit.cli:main"
[build-system] names the tool that builds the package. [project] is the metadata. [project.scripts] is the entry point: it says that a command named mlkit should call the function main in the module mlkit.cli. The installer creates that command for you, and its exit code is whatever main returns.The commands that install and build are shell commands, so they cannot run in the browser. Run them in a terminal:
# @read-only
# Create a virtual environment and install the package in editable mode
uv venv
uv pip install -e .
mlkit # runs mlkit.cli:main
# Build a wheel and a source archive into dist/
uv build
-e means editable: the installed package points at your src/ folder, so edits take effect without reinstalling. uv build writes a .whl file (a wheel, the ready-to-install format) and a .tar.gz source archive into dist/. The same flow works with pip install -e . and python -m build. Publishing to PyPI is a separate step that this lesson does not cover.module:function, import the module and call it.import importlib
import sys
import tempfile
import tomllib # tomllib needs Python 3.11 or newer
from pathlib import Path
PYPROJECT = """\
[project]
name = "mlkit"
version = "0.1.0"
[project.scripts]
mlkit = "mlkit.cli:main"
"""
CLI = '''\
def main() -> int:
print("mlkit says hello")
return 0
'''
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
(root / "pyproject.toml").write_text(PYPROJECT)
package = root / "src" / "mlkit"
package.mkdir(parents=True)
(package / "__init__.py").write_text('__version__ = "0.1.0"\n')
(package / "cli.py").write_text(CLI)
meta = tomllib.loads((root / "pyproject.toml").read_text())
print(meta["project"]["name"], meta["project"]["version"])
print(meta["project"]["scripts"])
# From the project root the package is NOT importable: only src/ holds it.
sys.path.insert(0, str(root))
importlib.invalidate_caches()
try:
importlib.import_module("mlkit")
except ModuleNotFoundError as err:
print("before install:", err)
# Putting src/ on the path is what `pip install -e .` achieves for you.
sys.path.insert(0, str(root / "src"))
importlib.invalidate_caches()
module_name, func_name = meta["project"]["scripts"]["mlkit"].split(":")
func = getattr(importlib.import_module(module_name), func_name)
print("exit code", func())
print("version", importlib.import_module("mlkit").__version__)
sys.path[:2] = []
for name in ("mlkit", "mlkit.cli"):
sys.modules.pop(name, None)Output:
mlkit 0.1.0
{'mlkit': 'mlkit.cli:main'}
before install: No module named 'mlkit'
mlkit says hello
exit code 0
version 0.1.0
uv pip install -e . created a working mlkit command, import mlkit worked from another directory, and uv build produced one wheel and one source archive.#A Plan for Failure: Retry with Backoff
One night the API your job calls answers slowly for ten seconds. Failing the whole run for that is a waste, and so is hammering the server again at once. The usual answer is a bounded retry: try a few times, wait longer between tries, then give up and let the error through. A decorator is the natural shape, because it wraps any function without changing its body (Decorators shows how).
import functools
import logging
import random
import sys
import time
logging.basicConfig(level=logging.INFO, stream=sys.stdout, format="%(levelname)s %(message)s", force=True)
log = logging.getLogger("retry")
def retry(attempts=4, base=0.5, retry_on=(TimeoutError, ConnectionError)):
"""Call the function again after a transient error, waiting longer each time."""
def decorator(fn):
@functools.wraps(fn)
def wrapper(*args, **kwargs):
for n in range(1, attempts + 1):
try:
return fn(*args, **kwargs)
except retry_on as err:
if n == attempts:
raise # out of attempts: the caller sees the real error
delay = base * 2 ** (n - 1) * random.uniform(0.5, 1.0)
log.warning("attempt %d/%d failed: %r; retrying in %.2fs", n, attempts, err, delay)
time.sleep(delay)
return wrapper
return decorator
calls = {"n": 0}
@retry(attempts=4, base=0.05) # a small base so the demo is quick
def fetch_scores():
calls["n"] += 1
if calls["n"] < 3:
raise TimeoutError("server took too long")
return [0.8, 0.3]
random.seed(7) # only so the printed delays are the same every run
print(fetch_scores(), "after", calls["n"], "calls")Output:
WARNING attempt 1/4 failed: TimeoutError('server took too long'); retrying in 0.03s
WARNING attempt 2/4 failed: TimeoutError('server took too long'); retrying in 0.06s
[0.8, 0.3] after 3 calls
base * 2 ** (n - 1)), so the server gets room to recover. The random.uniform(0.5, 1.0) factor is jitter: it spreads the waits out, so a hundred clients that failed together do not all retry at the same instant. Only the exception types in retry_on are retried, so a ValueError from a bug fails at once. And never retry a write blindly: if a timeout hides the fact that the first request succeeded, a retry can charge a customer twice.TimeoutError instead of hanging, and respect for the server's rate-limit headers, such as a Retry-After value, which tell you how long to wait.#A Production Checklist
Run through this before you hand a script to a scheduler. Each line points back to a section above or to an earlier lesson.
- Nothing in the service uses
print. Messages go throughloggingto stdout, at a level that fits. - Every error message names what failed (the row, the file, the setting), not just that something did.
- Secrets and config values are read from the environment, never from source, and are not written to logs.
- Configuration is parsed into typed fields once at startup, and a bad value stops the program before any work starts.
maintakesargvand returns an exit code, and 0 means the run worked.- Calls to other services have a timeout and a bounded retry with backoff for transient errors. Calling APIs in Python shows
raise_for_statusand timeouts. - Dependencies are listed in
pyproject.tomland installed into a virtual environment, so another machine gets the same ones. - A test calls
main([...])with a small input. Testing with pytest shows how.
#Common Mistakes
#Try It: A Logged, Configurable Evaluator
evaluate command that scores a few predictions at a threshold, writes one JSON log line per row, and exits with 1 when accuracy is below a minimum. The starter supplies the data, the formatter and configure_logging. You write build_parser and main.Tests: Expected: the first run logs four predicted lines, then done with accuracy 1.0, and prints exit code 0. The second run logs accuracy 0.75, then an ERROR line, and prints exit code 1.
argparse turns --min-accuracy into args.min_accuracy. Booleans add up as 0 and 1, so correct += predicted == label counts matches. When it works, change the minimum to 0.5 and confirm the exit code flips.--json-logs flag that switches between the text and JSON formatters.#Recap
logging module gives each message a level, a name and a destination, and a JSON formatter makes the fields searchable. Configuration belongs in the environment, parsed once at startup into a typed object that stops the program with every problem listed. A command-line interface lets whoever runs the job choose settings without editing source, and a main(argv) that returns an exit code is both testable and honest with schedulers. A retry decorator with growing, jittered waits survives brief outages without hammering the server. A small library declares its name, dependencies and commands in pyproject.toml, sits in a src folder, and installs with one command.Your app has ten modules and each logs through its own logger. Where should the handlers and the level be set up?