MyInternships.in

Python Files & Errors

Python Logging

The logging module is Python's built-in, professional way to record what your program is doing — far more powerful and configurable than sprinkling print() statements everywhere.


Why Not Just Use print()?

print() is fine for quick experiments, but it has no concept of severity, no timestamps, and no easy way to turn messages on or off in production. The logging module solves all of this: it tags every message with a level, a timestamp, and lets you send output to a file, the console, or both, without changing your code.

A First Logging Example

basicConfig and a simple log message
Python
import logging

logging.basicConfig(level=logging.INFO)
logging.info("Application started")
logging.warning("Disk space running low")
logging.error("Failed to connect to database")
Output
Output
INFO:root:Application started
WARNING:root:Disk space running low
ERROR:root:Failed to connect to database

Logging Levels

Every log message has a severity level. basicConfig(level=...) sets the minimum level that actually gets shown — anything below it is silently ignored, so you can turn verbosity up or down without touching your logging calls.

LevelNumberUse For
DEBUG10Detailed info useful only while developing
INFO20Confirmation that things are working as expected
WARNING30Something unexpected, but the program still works
ERROR40A serious problem — some function could not run
CRITICAL50A very serious error — the program may be unable to continue
💡

Set level=logging.DEBUG while developing to see everything, then switch to level=logging.WARNING in production so only real problems show up.

Logging to a File with a Handler

A handler decides where log messages actually go — the console, a file, or even a remote server. basicConfig can attach a filename directly for simple cases.

Sending logs to a file
Python
import logging

logging.basicConfig(
    filename="app.log",
    level=logging.INFO,
    format="%(asctime)s - %(levelname)s - %(message)s"
)

logging.info("User signed up")
logging.error("Payment failed for order 1024")
  • Import logging and call logging.basicConfig(level=...) once, near the start of your program.
  • Use logging.debug/info/warning/error/critical() instead of print() for real applications.
  • Only messages at or above the configured level are shown or saved.
  • format lets you add timestamps and level names automatically to every message.
ℹ️

For larger projects, create a named logger with logging.getLogger(__name__) instead of using the root logger directly — it makes it easy to tell which module a message came from.

Related Python Topics

Keep learning with these closely related lessons.

Ready to use your Python skills?

Find Python, data science and software internships and fresher jobs across India.

Browse Python Internships