Some text some message..
Back 🎨 Python logging Module 18 Aug, 2025

🌟 What is Logging?

🔹 A standard Python module to track events & messages while your program runs.
🔹 More powerful and professional than print().
🔹 Helps with debugging, monitoring, error tracking, and auditing.


🎭 Why use logging over print()?

🟢 Feature 📢 print() 📝 logging
Purpose Just shows output Tracks events systematically
Levels ❌ None ✅ Debug, Info, Warning, Error, Critical
File Support ❌ No ✅ Can log to files & servers
Formatting ❌ Limited ✅ Flexible (timestamps, filenames, line numbers)
Scalability ❌ Bad for large apps ✅ Perfect for big systems

🔑 Logging Levels (Severity Pyramid)

🔴 CRITICAL (50) – Very serious error, may crash
🟠 ERROR    (40) – Major issue, affects program flow
🟡 WARNING  (30) – Unexpected, but still running
🟢 INFO     (20) – General information
🔵 DEBUG    (10) – Detailed developer debugging

👉 Default level = WARNING (it hides DEBUG & INFO unless configured).


🛠️ Basic Setup

import logging

logging.basicConfig(
    level=logging.DEBUG,  # Show all messages (DEBUG and above)
    format="%(asctime)s - %(levelname)s - %(message)s"
)

logging.debug("Debugging details")
logging.info("Program is running fine")
logging.warning("Something looks odd!")
logging.error("An error happened!")
logging.critical("Critical failure!")

✅ Output Example:

2025-08-18 10:35:01,234 - DEBUG - Debugging details
2025-08-18 10:35:01,235 - INFO - Program is running fine
2025-08-18 10:35:01,236 - WARNING - Something looks odd!
2025-08-18 10:35:01,237 - ERROR - An error happened!
2025-08-18 10:35:01,238 - CRITICAL - Critical failure!

📂 Logging to a File

import logging

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

logging.info("This goes into app.log instead of console!")

➡️ Creates app.log file with your logs.


🎨 Custom Formatting

Available placeholders:

  • %(asctime)s → Time of log

  • %(levelname)s → Level name

  • %(message)s → Log message

  • %(filename)s → File name

  • %(lineno)d → Line number

  • %(name)s → Logger name

Example:

formatter = logging.Formatter("%(name)s | %(levelname)s | Line: %(lineno)d | %(message)s")

⚙️ Advanced: Logger + Handlers + Formatter

import logging

# Create logger
logger = logging.getLogger("my_app")
logger.setLevel(logging.DEBUG)

# File handler (only errors)
file_handler = logging.FileHandler("error.log")
file_handler.setLevel(logging.ERROR)

# Console handler (all logs)
console_handler = logging.StreamHandler()
console_handler.setLevel(logging.DEBUG)

# Format
formatter = logging.Formatter("%(asctime)s | %(name)s | %(levelname)s | %(message)s")
file_handler.setFormatter(formatter)
console_handler.setFormatter(formatter)

# Add handlers
logger.addHandler(file_handler)
logger.addHandler(console_handler)

# Logs
logger.debug("Debugging here")
logger.info("Informative message")
logger.error("Error goes to console + file")

🚦 Best Practices

✅ Always use logging, not print() for production
✅ Use correct log levels (debug for dev, info for flow, error for problems)
✅ Configure different handlers (console, file, email alerts, etc.)
✅ Add timestamps, filenames, line numbers for better debugging
✅ Keep separate log files (e.g., app.log, error.log)


Summary in One Line:
logging = The professional way to watch your code talk, with levels, colors, files, and control.