🚫 Python Errors and Exception Handling
Estimated reading: 3 minutes 287 views

Python Logging – Track Info, Warnings & Errors Efficiently

Introduction – Why Use Logging in Python?

Debugging with print() is fine—for toy scripts.

But in real-world applications, you need a robust and scalable way to:

  • Track what happened (and when)
  • Record errors and warnings
  • Write logs to files or external systems
  • Debug without cluttering production output

That’s where Python’s built-in logging module comes in.

In this guide, you’ll learn:

  • How Python logging works
  • Logging levels and use cases
  • How to log to a file
  • Formatting and configuring logs
  • Real-world practices for robust logging

Getting Started with Python Logging

import logging

logging.basicConfig(level=logging.INFO)
logging.info("This is an info message.")

Output:

INFO:root:This is an info message.

basicConfig() sets up the logging system and configures the default behavior.


Logging Levels Explained

Python logging uses levels to classify the importance of events:

LevelMethodUse For
DEBUGlogging.debug()Detailed information for debugging
INFOlogging.info()Confirmation that things work as expected
WARNINGlogging.warning()Something unexpected, non-breaking
ERRORlogging.error()A serious problem, but still running
CRITICALlogging.critical()Fatal error, app may crash

Example – Logging at Multiple Levels

logging.debug("Debugging message")
logging.info("Info message")
logging.warning("Warning message")
logging.error("Error message")
logging.critical("Critical error")

By default, only WARNING and above are shown unless you set a lower level.


Logging to a File

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

logging.info("File logging initialized.")

Creates app.log file with:

2025-05-14 21:00:00,123 - INFO - File logging initialized.

Great for persistent error tracking, especially in production.


Logging Formatter and Custom Configuration

Format Tokens:

TokenDescription
%(asctime)sTimestamp
%(levelname)sLog level
%(message)sLog message
%(name)sLogger name
%(lineno)dLine number
%(funcName)sFunction name

Advanced Configuration with logging.config

import logging.config

logging.config.dictConfig({
    'version': 1,
    'formatters': {
        'detailed': {
            'format': '%(asctime)s %(name)s [%(levelname)s]: %(message)s'
        }
    },
    'handlers': {
        'file': {
            'class': 'logging.FileHandler',
            'filename': 'advanced.log',
            'formatter': 'detailed'
        }
    },
    'root': {
        'handlers': ['file'],
        'level': 'INFO'
    }
})

logging.info("Configured with dictConfig.")

Real-World Use Case – Error Logging in try/except

try:
    x = 1 / 0
except ZeroDivisionError as e:
    logging.error("Exception occurred", exc_info=True)

Output with traceback:

ERROR:root:Exception occurred
Traceback (most recent call last):
  ...
ZeroDivisionError: division by zero

Use exc_info=True to include full stack trace.


Best Practices for Logging

Do This Avoid This
Use appropriate levels (info, error)Logging everything as print()
Use log files for long-term trackingOverwriting the same log file
Include traceback using exc_info=TrueHiding errors with vague messages
Use RotatingFileHandler for big filesLetting logs grow indefinitely

Summary – Recap & Next Steps

Python’s logging module provides a powerful, scalable way to track events, debug issues, and keep your programs stable in production.

Key Takeaways:

  • Use logging.debug(), info(), warning(), error(), and critical() as needed
  • Configure logging with basicConfig() or dictConfig()
  • Use log files and rotation for persistent tracking
  • Always log exceptions using exc_info=True

Real-World Relevance:
Used in web apps, data pipelines, automation scripts, and enterprise software to monitor health and troubleshoot effectively.


FAQ – Python Logging

What’s the default logging level?

WARNING. Only messages of warning, error, and critical are shown by default.

How do I log to both console and file?

Use multiple handlers:

handler1 = logging.StreamHandler()
handler2 = logging.FileHandler("app.log")

Then add both to the logger.

Can I rotate logs automatically?

Yes. Use RotatingFileHandler or TimedRotatingFileHandler from logging.handlers.

Is logging better than print for debugging?

Absolutely. Logging provides levels, formats, file output, and error tracebacks.

Can I suppress logs in production?

Yes. Set a higher logging level like WARNING or ERROR using basicConfig(level=logging.ERROR).


Share Now :
Share

Python Logging

Or Copy Link

CONTENTS
Scroll to Top