पाठ 32 / 49

Logging और Debugging

Print debugging की जगह logging module उपयोग करें और pdb व breakpoint() से code में step-by-step चलें।

logging module

logging levels, timestamps और destinations जोड़ता है, और code बदले बिना उसे बढ़ाया या घटाया जा सकता है।

import logging

logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
log = logging.getLogger(__name__)

log.info("Starting job")
log.warning("Disk at %d%%", 91)
try:
    1 / 0
except ZeroDivisionError:
    log.exception("Calculation failed")

breakpoint() और pdb

breakpoint() आपको उस line पर debugger में ले जाता है। n (next), s (step), c (continue) और p expr (print) उपयोग करें।

def total(prices):
    result = 0
    for p in prices:
        breakpoint()   # inspect p and result here
        result += p
    return result

Levels सोच-समझकर उपयोग करें: DEBUG विवरण के लिए, INFO milestones के लिए, WARNING अजीब घटनाओं के लिए, ERROR failures के लिए। Passwords या tokens कभी log न करें।