πŸ“ Python Tutorial β€” Logging Module

Introduction 🌟

The logging module in Python provides a flexible and powerful system for tracking events in your applications. Logging is essential for debugging, monitoring, diagnostics, and production-level error tracking.

Note

πŸ’‘ Better than using print() for debugging
πŸ’‘ Supports levels, handlers, formatting, and external log files
πŸ’‘ Used in real applications, APIs, automation, ML pipelines, and more

1. Why Use Logging Instead of print()? πŸ€”

  • βœ” You can control verbosity (DEBUG, INFO, WARNING, ERROR…)
  • βœ” Logs can be written to files, console, network, email
  • βœ” Can enable/disable logs without removing code
  • βœ” Timestamp, filename, and line numbers can be added automatically

2. Basic Logging Usage 🧱

basic_logging.py

import logging

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

βœ” Quick setup β†’ prints log messages to console

3. Logging Levels πŸ“Š

LevelValueUsage
DEBUG10Detailed debugging information
INFO20General information
WARNING30Something unexpected happened
ERROR40Function failed
CRITICAL50Application crash

4. Customizing log format 🎨

format_logging.py

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

logging.debug("Debugging app...")

βœ” `%(asctime)s` β†’ timestamp
βœ” `%(levelname)s` β†’ log level
βœ” `%(message)s` β†’ your message

5. Writing Logs to a File πŸ“„

file_logging.py

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

logging.error("Something went very wrong!")

βœ” Logs stored permanently for debugging or audits

6. Loggers, Handlers & Formatters (Recommended Structure) 🧩

For larger apps, you should configure logging using:

  • πŸ”Ή Logger β†’ the object you call .info(), .error(), etc.
  • πŸ”Ή Handler β†’ decides where logs go (file, console, network)
  • πŸ”Ή Formatter β†’ controls message formatting

logger_structure.py

import logging

logger = logging.getLogger("myapp")
logger.setLevel(logging.DEBUG)

handler = logging.FileHandler("log.txt")
handler.setLevel(logging.DEBUG)

formatter = logging.Formatter("%(levelname)s - %(message)s")
handler.setFormatter(formatter)

logger.addHandler(handler)

logger.debug("Debug message")
logger.info("Info message")

βœ” Modular
βœ” Scalable

7. Logging Exceptions (Important!) ⚠️

logging_exception.py

import logging

try:
    x = 10 / 0
except Exception:
    logging.exception("An error occurred")

βœ” Automatically prints traceback

8. Disable Logging Completely 🚫

disable_logging.py

logging.disable(logging.CRITICAL)

logging.error("This will NOT appear")

βœ” Useful in production builds

9. Logging from Multiple Modules πŸ“¦

module_logging.py

# file: module1.py
import logging
logger = logging.getLogger(__name__)
logger.info("Module 1 started")

βœ” Automatically names logger after module

10. Rotating Log Files πŸ”„

For long-running apps, use rotating logs to prevent giant log files.

rotating_logs.py

from logging.handlers import RotatingFileHandler
import logging

handler = RotatingFileHandler(
    "app.log", maxBytes=2000, backupCount=3
)

logger = logging.getLogger("rotator")
logger.addHandler(handler)

logger.warning("Test rotating logs")

βœ” Automatically rotates files when size limit reached

11. Timed Rotating Logs ⏱️

timed_rotating_logs.py

from logging.handlers import TimedRotatingFileHandler
import logging

handler = TimedRotatingFileHandler(
    "timed.log", when="midnight", interval=1
)

logger = logging.getLogger("timer")
logger.addHandler(handler)

logger.info("Daily log started")

βœ” Useful for daily, hourly or weekly logs

12. JSON Logging (for APIs & ML pipelines) πŸ“¦

json_logging.py

import logging, json

class JSONFormatter(logging.Formatter):
    def format(self, record):
        return json.dumps({
            "level": record.levelname,
            "message": record.msg,
            "time": self.formatTime(record)
        })

logger = logging.getLogger("json")
handler = logging.StreamHandler()
handler.setFormatter(JSONFormatter())

logger.addHandler(handler)
logger.error("API failed")

βœ” Ideal for structured logs

Logging Cheat Sheet πŸ“˜

Method / LevelUsage
logging.debug()Detailed developer logs
logging.info()Status updates
logging.warning()Potential problem
logging.error()Recoverable error
logging.critical()Severe failure
logging.exception()Log traceback automatically
FileHandlerWrite logs to file
StreamHandlerConsole logging
RotatingFileHandlerAuto-rotate logs
TimedRotatingFileHandlerRotate at intervals

Best Practices πŸ’‘

  • βœ” Never use print() for debugging in production
  • βœ” Use different log levels appropriately
  • βœ” Add timestamps & module names for clarity
  • βœ” Rotate logs to avoid huge files
  • βœ” Use structured logging (JSON) for APIs
  • βœ” Avoid logging sensitive information (passwords, tokens)

Conclusion πŸŽ‰

>>β€œLogging turns invisible program behavior into clear, searchable insights.” ✨

You now fully understand the Logging module in Python! Want the next topic? Try Debugging, Error Handling, Traceback, or Unit Testing. Just tell me! 😊