🚫 Python Errors and Exception Handling
Estimated reading: 3 minutes 26 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 :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

Python Logging

Or Copy Link

CONTENTS
Scroll to Top