Keyboard Shortcuts N Next post
P Previous post
S Save / unsave
R Read aloud
T Toggle theme
/ Focus search
Esc Close panels
🔥
Ready to read...
debugging Module 6 - File Handling & Errors Python Python Basics Python Programming: From Zero to Real-World Applications

Logging in Python - Better Than Print

Reviewed & accurate
AI Summary

What You Will Learn

Intermediate

  • The logging module and log levels
  • Logging to file and console
  • Format and handlers
Terminalpython
import logging

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

# Log levels (lowest to highest)
logging.debug("Debug info - detailed troubleshooting")
logging.info("Info - normal operation")
logging.warning("Warning - something unexpected")
logging.error("Error - something failed")
logging.critical("Critical - system cannot continue")

Log Levels

LevelWhen to useNumeric
DEBUGDetailed diagnostic info10
INFOConfirm things work20
WARNINGSomething unexpected, still working30
ERRORSomething failed40
CRITICALSystem cannot continue50
Use logging, not print
print() is for development. logging is for production: timestamps, levels, file output, and you can control verbosity without changing code.

Practical Exercise

import logging and configure with basicConfig
Log at each level: debug, info, warning, error
Log to a file: filename='app.log'
Change level to WARNING - see debug/info disappear
Add format: '%(asctime)s - %(levelname)s - %(message)s'

Key Takeaways

  • logging is better than print: levels, files, formatting.
  • 5 levels: DEBUG < INFO < WARNING < ERROR < CRITICAL.
  • basicConfig: set level, format, filename.
  • Set level=logging.WARNING to hide debug/info.
  • Use logging.exception() inside except blocks - includes traceback.
Previously: Lesson 41 covered context managers.
Today: You learned: Replace print() with proper logging.
Next: Module 6 complete! Module 7 begins with lesson 43.
Test Your Knowledge
How did you find this?

Comments

Join the discussion! Sign in with your Google or Blogger account, or comment as Anonymous - no account needed. For quick questions, also reach me on Telegram @cytestch.

Comments