๐ชต Logging
Logging is a means of tracking events that happen when some software runs.
Mastering this concept will significantly boost your Python data science skills!
๐ป Code Example:
import logging import logging.handlers import json from pathlib import Path # 1. Root logger basic setup (development) logging.basicConfig( level=logging.DEBUG, format="%(asctime)s | %(levelname)-8s | %(name)s | %(message)s", datefmt="%Y-%m-%d %H:%M:%S", ) root = logging.getLogger("pynfinity") root.info("Platform started โ santoshtvk/pynfinity") root.warning("Config missing โ using defaults") # 2. File + console handlers (production pattern) log_path = Path("pynfinity.log") logger = logging.getLogger("pynfinity.app") logger.setLevel(logging.DEBUG) logger.propagate = False # Don't bubble to root logger fmt = logging.Formatter("%(asctime)s | %(levelname)-8s | %(message)s") # Rotating file (max 5MB, keep 3 backups) fh = logging.handlers.RotatingFileHandler( log_path, maxBytes=5*1024*1024, backupCount=3, encoding="utf-8" ) fh.setLevel(logging.WARNING) fh.setFormatter(fmt) ch = logging.StreamHandler() ch.setLevel(logging.DEBUG) ch.setFormatter(fmt) logger.addHandler(fh) logger.addHandler(ch) logger.debug("Debug detail visible in console only") logger.info("User santoshtvk completed Infinite Python ๐") logger.warning("Payment gateway response slow (>2s)") logger.error("Could not send FCM notification to user dhruv") # 3. Structured JSON logging class JSONFormatter(logging.Formatter): def format(self, record: logging.LogRecord) -> str: return json.dumps({ "time" : self.formatTime(record, "%Y-%m-%dT%H:%M:%S"), "level" : record.levelname, "logger" : record.name, "message": record.getMessage(), "module" : f"{record.filename}:{record.lineno}", }) json_logger = logging.getLogger("pynfinity.json") json_handler = logging.StreamHandler() json_handler.setFormatter(JSONFormatter()) json_logger.addHandler(json_handler) json_logger.setLevel(logging.INFO) json_logger.info("Structured log entry โ ready for ELK / Datadog") # 4. Exception logging try: _ = 1 / 0 except ZeroDivisionError: logger.exception("Caught math error โ traceback auto-included") # Cleanup log_path.unlink(missing_ok=True)
Keep exploring and happy coding! ๐ป