Python Logging to File: A Production-Ready Guide
For a Python script or service that needs a local log file, configure a handler, choose an explicit path and encoding, and verify rotation. Console output is also a valid production destination when systemd, a container runtime or another collector persists it; an unattended terminal alone is not durable storage.
The current Python logging reference documents loggers, handlers, formatters and filters. The examples below target supported Python 3 releases; basicConfig(encoding=...) requires Python 3.9 or later. Run each example independently at the application entry point.
Table of Contents
- The Foundation Basic File Logging Setup
- Adding Structure with Formatters and Levels
- Managing Log Files with Rotation
- Advanced Configuration with Dictionaries and Files
- Production Patterns for Modern Applications
- Troubleshooting Common Logging Issues
The Foundation Basic File Logging Setup

A working file logger can be as simple as a single basicConfig() call. The simplest reliable starting point looks like this:
import logging
logging.basicConfig(
filename="app.log",
level=logging.INFO,
filemode="a",
encoding="utf-8",
)
logging.info("Application started")
logging.warning("Cache miss for user profile")
The filename argument tells Python where to write. The level controls which messages are kept, so INFO drops low-level debug noise while still preserving useful operational events. The filemode choice matters, too, because 'a' appends by default behavior and 'w' overwrites the file on each run, which is useful for short-lived scripts but risky for production incident review.
Why the defaults matter
Appending is usually the safer operational choice because it preserves history across restarts. That history is what helps a developer reconstruct the order of events after a crash or failed deploy. Overwrite mode has its place in test harnesses, local utilities, and repeatable demos, but it can erase the exact evidence a production investigation needs.
The encoding choice matters as well. Real Python's logging guidance recommends UTF-8 so logs can hold a wide range of characters reliably, which is a practical requirement for multilingual systems and oddball error messages (Real Python logging guide). If the service ever emits non-ASCII user input, bad encoding settings become a hidden source of logging failure.
A good first habit is to write one focused startup message and one event message, then open the file immediately and verify the path, level, and mode. That tiny loop catches configuration mistakes faster than waiting for an incident.
For a concrete use case, see how a Python workflow can feed data pipelines in Automate CS2 data collection with Python. The logging pattern is the same, the task changes.
Practical rule: start with a file name, a level, and append mode. Anything more complex before that usually hides the real problem instead of solving it.
The reason this setup feels so clean is historical, not accidental. Python logging shipped as part of the standard library early on, so file output became a built-in observability pattern rather than a third-party dependency. That design choice still pays off because developers can rely on the same core concepts in both old and new codebases.
Adding Structure with Formatters and Levels
Raw lines in a file are better than nothing, but they age badly the moment an app gets busy. A useful log line should answer three questions quickly, who emitted it, what happened, and where in the code it happened. The formatter is what turns a plain message into something that can survive a production review.
A stronger setup looks like this:
import logging
logging.basicConfig(
filename="app.log",
level=logging.INFO,
filemode="a",
encoding="utf-8",
format="%(asctime)s %(levelname)s %(name)s %(funcName)s:%(lineno)d %(message)s",
)
logger = logging.getLogger(__name__)
logger.info("Payment gateway timeout for transaction_id=xyz")
That format string adds timestamps, severity, logger name, function name, and line number. Those fields turn a dead-simple message into a record that can be traced back to a module and a code path without guesswork.
Picking the right level
The built-in levels follow a simple severity ladder, DEBUG, INFO, WARNING, ERROR, and CRITICAL. Sentry's Python logging guide describes that progression clearly and notes that WARNING and above are the default threshold if nothing is configured (Sentry logging guide). That default matters because many teams assume debug output is missing when Python is just filtering it out.
A practical split usually looks like this:
- DEBUG for diagnostic state, local reproduction, and code path verification.
- INFO for normal business events, service milestones, and successful operations.
- WARNING for degraded conditions that still let the system continue.
- ERROR for failed operations that need attention.
- CRITICAL for failures that threaten the service itself.
Logs become useful when they can be searched without reading the whole file. Context in the line is cheaper than context in a ticket.
The biggest mistake here is to keep messages too generic. “Task failed” is almost useless. “Payment gateway timeout for transaction_id=xyz” gives an operator something to search, correlate, and alert on.
There's also a maintainability angle. A consistent format across modules makes log files readable even when several developers touch the same service. That consistency is why teams often standardize the format string early and leave it alone unless they're moving to structured output.
If a larger logging layout is needed later, the file format used here can be mirrored in a more centralized setup, as shown in this logging format reference.
Managing Log Files with Rotation
A file that never rotates eventually becomes a storage problem, a readability problem, and sometimes an outage problem. Production systems need a retention strategy, not just a destination. Rotation is the simplest reliable answer because it keeps active logs manageable while archiving history in predictable chunks.
For size-based rotation, RotatingFileHandler is the standard option:
import logging
from logging.handlers import RotatingFileHandler
from pathlib import Path
Path("logs").mkdir(parents=True, exist_ok=True)
logger = logging.getLogger("app")
logger.setLevel(logging.INFO)
logger.propagate = False
handler = RotatingFileHandler(
"logs/app.log",
maxBytes=5_000_000,
backupCount=5,
encoding="utf-8",
)
formatter = logging.Formatter("%(asctime)s %(levelname)s %(message)s")
handler.setFormatter(formatter)
logger.addHandler(handler)
logger.info("Rotation-ready logging configured")
Both maxBytes and backupCount must be positive for size-based rotation. Five backups plus the active file give roughly 30 MB at this setting, not a strict quota: an individual record can exceed the threshold. Configure this logger once; adding the same handler repeatedly duplicates records. Set directory permissions for the service account rather than making logs world-writable.
Size-based versus time-based rotation
TimedRotatingFileHandler is the better fit when log cadence matters more than file size. Daily rotation is common for auditability, while hourly rotation can help with high-volume services where operators want clean time slices. The choice depends on how the logs are read, not just how they're written.
from logging.handlers import TimedRotatingFileHandler
handler = TimedRotatingFileHandler(
"logs/app.log",
when="midnight",
utc=True,
backupCount=7,
encoding="utf-8",
)
Use the timed handler as an alternative to the rotating handler in the previous setup, attaching the formatter and handler to the logger. With utc=True, midnight means UTC. Rollover occurs when a record is emitted after the deadline, not from an independent timer. See the handler reference for retention and rollover behavior.

The operational trade-off is simple. Size-based rotation reacts to volume, while time-based rotation reacts to schedule. Busy services often benefit from size-based rollover because bursts can happen at any time, but scheduled rotation can be easier for compliance, incident review, and batch workflows.
The practical mistake is leaving a single writable file in place for months. That works in a demo and fails in a real service with real traffic. Rotation is not extra polish, it is basic file hygiene.
For a deeper operational perspective on rotation policy, see the complete guide to logrotate.
Advanced Configuration with Dictionaries and Files
Hard-coding logging setup directly in application code works at first, then gets messy. As the number of modules, handlers, and environments grows, the logging config should move out of business logic. dictConfig gives Python teams a clean middle ground because the whole logging tree can live in one dictionary instead of being spread across imports and setup functions.
A compact example looks like this:
import logging.config
LOGGING = {
"version": 1,
"disable_existing_loggers": False,
"formatters": {
"standard": {
"format": "%(asctime)s %(levelname)s %(name)s %(message)s"
}
},
"handlers": {
"file": {
"class": "logging.FileHandler",
"filename": "app.log",
"formatter": "standard",
"level": "INFO",
"encoding": "utf-8",
}
},
"root": {
"handlers": ["file"],
"level": "INFO",
},
}
logging.config.dictConfig(LOGGING)
This pattern keeps configuration declarative. The application reads the dictionary, Python builds the handlers, and the rest of the code only asks for loggers by name. That separation is easier to review in code review and easier to override per environment.
Why external files help operations teams
A trusted JSON or YAML file can supply this dictionary. Loading a file does not automatically reload configuration when it changes: implement and test an explicit restart or reload path. Treat logging configuration as executable configuration because custom factories can import and call code. Never accept an untrusted user-supplied dictionary.
A useful mental model is this, application code emits records, configuration decides where they land. Keeping those concerns separate makes rollback safer and reduces the risk of a logging tweak breaking the core app. It also makes it easier to standardize logging across multiple services in the same estate.
Operational rule: if a logging change requires editing ten files, the setup is already too coupled.
Fivenines can sit alongside this kind of setup as a monitoring destination for the service as a whole, but the logging configuration itself should still stay clean and predictable. That's the point of moving from inline setup to config-driven design.
When teams start with basicConfig() and later grow into dictConfig, they usually keep the same format and level choices. The difference is control. A file or dictionary gives DevOps and SRE teams a place to manage logging without touching the code path that handles users.
Production Patterns for Modern Applications
File logging is still useful in production, but modern systems rarely stop at plain text files. The better pattern is to treat file output as one destination among several, while keeping records structured enough to move into dashboards, search tools, or incident systems later. JSON is the cleanest way to do that because it preserves fields without forcing brittle string parsing.
Use a real JSON serializer rather than hand-built “JSON-like” text. This standalone example round-trips quotes and newlines and checks every line can be parsed:
import json
import logging
from pathlib import Path
class JsonFormatter(logging.Formatter):
def format(self, record):
return json.dumps({"level": record.levelname,
"logger": record.name,
"message": record.getMessage()}, ensure_ascii=False)
logger = logging.getLogger("json-demo")
logger.setLevel(logging.INFO)
logger.propagate = False
handler = logging.FileHandler("json-demo.log", encoding="utf-8")
handler.setFormatter(JsonFormatter())
logger.addHandler(handler)
logger.info('Example with "quotes" and a newline\nkept in one JSON record')
handler.flush()
for line in Path("json-demo.log").read_text(encoding="utf-8").splitlines():
assert isinstance(json.loads(line)["message"], str)
logger.removeHandler(handler)
handler.close()
Use non-secret correlation IDs, and redact tokens, credentials and unnecessary personal data before emission. This minimal formatter omits exception details; add explicitly redacted exception fields when required.
Concurrency changes the design
For latency-sensitive services, a QueueHandler can pass records to a QueueListener with one file-writing handler. Standard logging supports threads in one process, but multiple processes writing the same file require a coordinated single writer or an external collector. The Python logging cookbook documents these patterns.
A queue moves work rather than guaranteeing delivery. Define what happens when it fills, monitor drops, and stop the listener during graceful shutdown so queued records are drained. An in-memory queue does not survive a crash. Measure overhead and loss behavior with the actual workload before replacing synchronous logging.
Containerized services need a different default
In Docker and similar runtimes, stdout and stderr are usually the cleanest defaults because the platform can collect, forward, and persist the stream. File handlers still have a role when a persistent volume is mounted or when a local artifact is needed for offline review, but they should be intentional, not accidental. In containerized environments, local file logging without volume planning often creates invisible data loss.
When file handlers still win
Local files are still valuable for:
- Incident reconstruction when the service needs a persistent on-host record.
- Air-gapped or constrained environments where external collectors are limited.
- Tools and agents that need a durable artifact beside a job run.
The trick is to use the right output for the deployment model instead of assuming every service should behave like a daemon on bare metal. That's where maintainability improves. Each environment gets a logging path that matches how the platform stores and moves data.
For performance-oriented monitoring alongside application logs, monitor application performance remains a useful operational companion. Logging and monitoring solve different problems, but they work best together when the event stream is structured and the output path is deliberate.

Troubleshooting Common Logging Issues
The most frustrating logging bug is the one where the code looks right and the file stays empty. In practice, that usually has less to do with syntax and more to do with handler state, import order, or a configuration that never really took effect. The first thing to check is whether another module configured logging before the file handler was added.
basicConfig() does nothing when the root logger already has handlers, unless force=True is supplied. force was added in Python 3.8 and removes and closes existing root handlers. Use it only when the application owns that configuration; a library should not reset its host application’s logging. See the logging reference.
A practical debugging checklist
- Verify logger level. Make sure the logger isn't set higher than the messages being emitted.
- Check handler level. The handler can filter messages even when the logger is open.
- Inspect file path and permissions. An unwritable path looks like a logging bug until the filesystem says otherwise.
- Examine formatters. A bad formatter can hide useful output or make lines look blank.
- Look for exceptions. Silent errors elsewhere in startup often prevent the file handler from being reached.
- Address the root logger. Pre-existing root handlers can override the expected file setup.
- Review shutdown behavior. Buffered records need a clean exit so the last messages reach disk.
A quick inspection step helps too. Checking logging.getLogger().handlers shows whether the root logger already has active handlers, which usually explains why a new basicConfig() call seems ignored. If modules import logging code before the application entry point configures it, the startup order can decide the outcome.
Path handling deserves attention as well. Absolute paths remove ambiguity when a service starts from a different working directory, and write permissions should be verified before assuming the handler is broken. In containerized deployments, the file may be technically configured correctly and still never appear because the path isn't writable inside the runtime.
For a broader operational parallel, how to detect memory leak is a useful reminder that invisible failures usually come from runtime state, not just syntax. Logging issues and memory issues both get harder when operators trust the code more than the environment.
The safest habit is to test logging during startup, not after a failure. Emit a known message, confirm the file exists, and make sure the expected handler wrote to the expected location. That simple check catches the empty-file problem before it becomes a production blind spot.
Configure the output path, permissions, levels and retention deliberately, then test normal events, exceptions, rotation and graceful shutdown. Fivenines log monitoring can attach logs from configured systemd journal units to incidents alongside infrastructure context; a Python FileHandler does not automatically send its files there. Choose journald output or a separate file collector according to your deployment.