Most beginners debug with print(). That works until the program runs on a server, at night, and fails. Python’s built-in logging module records what happened, when, and how serious it was, and you can switch detail on or off without editing your code.
A first setup
import logging
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s: %(message)s")
logger = logging.getLogger(__name__)
logger.info("Import started")
logger.warning("Row 42 has no email")
Each line now carries a timestamp, a level and the module name, which makes problems much easier to trace.
The five levels
- DEBUG: detailed information for developers.
- INFO: normal progress, such as “500 rows imported”.
- WARNING: something unexpected that did not stop the program.
- ERROR: an operation failed.
- CRITICAL: the program cannot continue.
Set the level to DEBUG while developing and INFO or WARNING in production. Lower levels are simply ignored.
Logging exceptions
try:
process(row)
except Exception:
logger.exception("Failed to process row %s", row_id)
logger.exception records the full traceback, which is exactly what you need when investigating a failure later.
Writing to a file
Add filename="app.log" to basicConfig, or use a RotatingFileHandler so the file does not grow forever. In Docker and cloud platforms, logging to standard output is usually preferred; the platform collects it.
Good habits
- Use one logger per module:
logging.getLogger(__name__). - Pass values as arguments (
logger.info("User %s logged in", user_id)) rather than building strings yourself. - Never log passwords, tokens or full personal data.
- Log enough context to understand an error without the debugger.
Related: Python exception handling and Python for automation: your first useful script.
These topics are practised with projects in our Python Full Stack course in Bangalore.
Book a free demo class at our BTM Layout centre, and ask a counsellor for batch details.
